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

 

转载于:https://www.cnblogs.com/NExt-O/p/9757853.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值