JS系列-继承

18 篇文章 1 订阅

JS如何实现继承

第一种使用call。

在这里插入图片描述
但是这种方法会存在函数不能使用问题,引出下面方法。

第二种使用原型链

在这里插入图片描述
这种方法是利用原型链,那么会存在共享问题,既然都共享一个原型那么修改其中的数组那么其他实例也会跟着变

 var s1 = new Child2();
  var s2 = new Child2();
  s1.play.push(4);
  console.log(s1.play, s2.play);
  // (4) [1, 2, 3, 4] (4) [1, 2, 3, 4]

其中父类也跟着变了
在这里插入图片描述

第三种:call和原型链组合(将前两种组合)

  function Parent3 () {
    this.name = 'parent3';
    this.play = [1, 2, 3];
  }
  function Child3() {
    Parent3.call(this);
    this.type = 'child3';
  }
  Child3.prototype = new Parent3();
  var s3 = new Child3();
  var s4 = new Child3();
  s3.play.push(4);
  console.log(s3.play, s4.play);

在这里插入图片描述

此时尝试在父类添加方法是可以直接使用的
在这里插入图片描述
那么之前俩种的方法问题都解决了,这里又多了Parent3构造函数会执行一次
Child3.prototype = new Parent3();

第四种: 组合继承的优化1

 function Parent4 () {
    this.name = 'parent4';
    this.play = [1, 2, 3];
  }
  function Child4() {
    Parent4.call(this);
    this.type = 'child4';
  }
  Child4.prototype = Parent4.prototype;
  var s3 = new Child4();
  var s4 = new Child4();
  console.log(s3)

在这里插入图片描述注意红线这里,child4实例的构造函数是parent4,这是错的,应该是它自己本身child4才对

第五种: 组合继承的优化2-寄生组合继承(Extend原理)

function Parent5 () {
    this.name = 'parent5';
    this.play = [1, 2, 3];
  }
  function Child5() {
    Parent5.call(this);
    this.type = 'child5';
  }
  Child5.prototype = Object.create(Parent5.prototype);
  Child5.prototype.constructor = Child5;

ES6中的extend 被bable编译后就是使用的寄生继承。

参考文章

总结

  1. call继承-问题》父类中的函数无法使用
  2. 原型链继承-问题》如果改了原型属性则会影响所有实例
  3. call+原型链-问题》多执行一次构造函数
  4. 寄生继承1-问题》实例的构造函数是父类的
  5. 寄生组合继承》extend
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值