JavaScript 对象继承


原型继承:

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


function animal(footnum,eyescolor,feathercolor){ //夫类
    this.foot = footnum;
    this.eyes = eyescolor;
    this.feather = feathercolor;
  }
  animal.prototype.eat = function(){
    alert("eatting");
  }
  
 function bird(){ //子类
 
 }

 bird.prototype = new animal(5,"black","red"); //继承
/*
不能使用对象字面量创建原型方法。因为这
样做就会重写原型链 如:
bird.prototype ={
  fly : function(){
    alert('flying');
  }
}
*/
 bird.prototype.fly=function(){   

   alert('fly');
 }
var eagle = new bird(); //对象 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,name,age,tall);
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

 

posted @ 2018-10-08 22:59  next_ojp  阅读(304)  评论(0编辑  收藏  举报