ES5 / ES6 实现继承

ES5

组合继承

    function Parent(value) {
      this.val = value
    }
    Parent.prototype.getValue = function () {
      console.log(this.val);
    }
    function Child(value) {
      Parent.call(this, value)
    }
    Child.prototype = new Parent()
    const child = new Child(1)
    child.getValue()//1

我们来研究一下这段代码到底想做什么:子类Child想要继承父类Parent的属性val和方法getValue。

一般我们所说的继承,是继承父类的prototype,所以父类的getValue方法应添加到父类的prototype中,而不是通过 this.getValue = function(){} 添加到父类的构造函数中。

然后Child想要继承属性val,所以通过调用父类构造函数的方式来继承,而非直接在自己的构造函数中写 this.val = value 来继承,这样体现不出继承的意义,因为相当于是直接给子类添加了val属性而不是继承了父类的val属性。

虽然这例子可能本身就比较刻意,但是我们只要通过这个例子能理解继承的思想即可。

理解了这段代码的想法,也能发现这种方式的缺点所在了:那就是在这个过程中调用了父类的构造函数,所以在子类的原型中多了不需要的父类属性,即原型链上有两个val了,存在内存上的浪费

可以用其他继承方式来解决这种问题,比如寄生组合继承。

寄生组合继承

这里就不多作分析了,自行研究哦~

    function Parent(value) {
      this.val = value
    }
    Parent.prototype.getValue = function () {
      console.log(this.val)
    }
    function Child(value) {
      Parent.call(this, value)
    }
    Child.prototype = Object.create(Parent.prototype, {
      constructor: {
        value: Child,
        enumerable: false,
        writable: true,
        configurable: true
      }
    })

    const child = new Child(1)

    child.getValue() // 1 

ES6

ES6的class和extends语法其实就是ES5继承语法的语法糖,class的本质还是函数

    class Parent {
      constructor(value) {
        this.val = value
      }
      getValue() {
        console.log(this.val);
      }
    }
    class Child extends Parent {
      constructor(value) {
        super(value)
        this.val = value
      }
    }
    let child = new Child(1)
    child.getValue()//1
    console.log(child);

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值