js继承

a.借助构造函数实现继承

function Parent(){
     this.name='大明'
 };
 Parent.prototype.say=function(){
      alert(this.name);
}
 function Child(){
     Parent.call(this);   //this表示Child,继承Parent的属性和方法
     this.type='child';
 }
 var p=new Child();
 console.log(p.name);    //大明
 console.log(p.type);    //child
 p.say();    //TypeError

特点:p既有name属性,也有type属性,但是没有say方法。
缺点:构造函数只能继承父类构造函数里面的方法,无法继承父类原型对象上的方法。

b.借助原型链实现继承

 function Parent(){
     this.name='大明';
     this.eat=[1,2,3];    //引用数据类型
  };
  Parent.prototype.say=function(){
       alert(this.name);
 }
  function Child(){
      this.type='child';
  }
  Child.prototype=new Parent();
  var p=new Child();
  console.log(p);   //name、type属性和say方法都有
  var p1=new Child();
  var p2=new Child();
  p1.name='小明';
  console.log(p1.name,p2.name);   //小明  大明
  p2.eat.push(4);
  console.log(p1.eat,p2.eat);    //[1,2,3,4]   [1,2,3,4]

特点:不仅可以继承父类上的方法,还可以继承父类原型上的方法。
缺点:当父类中包含引用类型属性值时,由子类创建的多个实例中,只要其中一个实例引用属性只发生修改,其他实例的引用类型属性值也会立即发生改变。

c.组合方式继承

function Parent(){
    this.name='大明';
    this.eat=[1,2,3];    //引用数据类型
 };
 function Child(){
     Parent.call(this);      //构造函数继承
     this.type='child';
 }
 Child.prototype=new Parent();    //原型链继承
 var p1=new Child();
 var p2=new Child();
 p2.eat.push(4);
 console.log(p1.eat,p2.eat);    //[1,2,3]   [1,2,3,4]

组合式继承也是实际开发中最常用的继承方式,解决了以上两种继承方式的问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值