码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 对象继承

时间:2018-10-09 00:52:53      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:font   eth   类继承   code   优点   anim   cti   小明   black   


原型继承:

  这种原型继承的特点:既继承了父类的模板,又继承了父类的原型对象。优点是继承了父类的模板,
    又继承了父类的原型对象,缺点就是父类实例传参,不是子类实例化传参,不符合常规语言的写法。

 1 function animal(footnum,eyescolor,feathercolor){ //夫类
 2   this.foot = footnum;
 3   this.eyes = eyescolor;
 4   this.feather = feathercolor;
 5 }
 6 animal.prototype.eat = function(){
 7   alert("eatting");
 8 }
 9 
10 function bird(){ //子类
11 
12 }
13 bird.prototype.fly=function(){
14   alert(‘fly‘);
15 }
16 bird.prototype = new animal(5,"black","red"); //继承
17 
18 var eagle = new bird(); //对象
19 eagle.eat();

 

 

 


 

类继承:

  继承了父类的模板,不继承了父类的原型对象。优点是方便了子类实例传参,
  缺点就是不继承了父类的原型对象

 1 function Person(name,age,tall){
 2   this.name = name;
 3   this.age = age;
 4   this.tall = tall;
 5 }
 6 Person.prototype.gether = function(){
 7   alert("gether");
 8 }
 9 
10 function boy(name,age,tall,face){
11 //call/apply Person.apply(this,[name,age,tall]);
12   Person.call(this);
13   this.face = face;
14 }
15 boy.prototype.play = function(){
16   alert("playing");
17 }
18 
19 var boys = new boy("小明",12,160,"circle");
20 boys.play();

 

 

 


 

组合继承:(推荐)

  既继承了父类的模板,又继承了父类的原型对象。优点方便了子类实例传参,
  缺点就是Boy.pertotype = new Persion() 函数又实例一次,函数内部变量又重复实例一次,
  大程序时候会很好性能。

 1 // 父类 
 2 function Person(name,age){ 
 3   this.name = name; 
 4   this.age = age; 
 5 }
 6 // 父类的原型对象属性 
 7 Person.prototype.id = 10;
 8 // 子类 
 9 function Boy(name,age,sex){ 
10 //call apply 实现继承
11 Person.call(this,name,age);
12   this.sex = sex;
13 }
14 // 原型继承实现 参数为空 代表 父类的实例和父类的原型对象的关系了
15 Boy.prototype = new Person();
16 var b = new Boy(‘c5‘,27,‘男‘); 
17 alert(b.name)// c5 
18 alert(b.id)//10

 

JavaScript 对象继承

标签:font   eth   类继承   code   优点   anim   cti   小明   black   

原文地址:https://www.cnblogs.com/NExt-O/p/9757853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!