js原生深入,手写常见的几种继承方式

  1. 原型链继承
function Parent() {
   this.name = '小头'
  }

  function Child() {
   this.age = 6;
  }
  const rest = new Parent();
  Child.prototype = rest;
  const res = new Child();
  console.log(res.name) //小头

缺点:当继承的属性有引用值时,改变后,父子中这个属性都会变化
看下面例子:

function Parent() {
   this.name = '小头';
   this.hobby = ['唱歌','爬山'];
  }

  function Child() {
   this.age = 6;
  }
  const rest = new Parent();
  Child.prototype = rest;
  const res = new Child();
  rest.hobby.push('零食','玩');
  console.log(res.hobby) // ["唱歌", "爬山", "零食", "玩"]

还有一个缺点是不能向继承的父级构造函数传递参数
入代码片

  1. 盗用构造函数
function Parent(name) {
      this.name = name;
     }

     function Child() {
      Parent.call(this,'小头');
      this.age = 6;
     }

     const res = new Child();
     console.log(res.name);

缺点:只能继承构造函数上的属性和方法,不能继承原型上的属性和方法
看下面例子:

function Parent(name) {
      this.name = name;
     }

     Parent.prototype.hobby = '唱歌';
     function Child() {
      Parent.call(this,'小头');
      this.age = 6;
     }
     const res = new Child();
     console.log(res.hobby);// undefined
  1. 组合继承
function Parent(name) {
      this.name = name;
     }
     Parent.prototype.hobby = '唱歌';
     function Child() {
      Parent.call(this,'小头');
      this.age = 6;
     }

     Child.prototype = new Parent();
     const res  = new Child();
     console.log(res.name); //小头
     console.log(res.hobby); //唱歌

缺点:每次实例化子对象都会在子对象的构造函数和原型上生成相同的属性和方法,也就是产生了两份。

  1. 寄生式继承
function clone(obj){
      const F = function () {};
      F.prototype = obj;
      return new F();
     }

     function test(obj) {
      let res = clone(obj);
      res.name = '小头';
      return res
     }
     const s = {
      name: '大头'
     }

     let res = test(s);
     console.log(res.say)

5.寄生式组合继承

function Parent(name) {
      this.name = name;
     }

     function Child(name) {
      Parent.call(this,name);
      this.age = '6';
     }
     Child.prototype = Object.create(Parent.prototype);
     const res = new Child('小头');
     console.log(res.name) //小头

到目前为止,寄生式组合继承是最完善的继承方法了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值