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);