引言
在 ES5 中,继承的方式有原型继承,构造继承,原型组合继承,寄生式继承,寄生组合继承。
其实原型组合继承就是原型继承与构造继承的组合,而寄生组合继承则是寄生式继承和构造继承的组合。不尽会猜想是否寄生式继承是原型继承的某种替代方案?如果是的话,那究竟是为什么要选择寄生继承呢?请往下看:
继承方式
1. 原型组合继承
function Father(){
this.msg = "Hello"
}
Father.prototype.say = function(){console.log(this.msg)}
function Child(){
Father.call(this); // 第一次:通过 call 调用父构造函数
this.childMsg = 'child';
}
Child.prototype = new Father(); // 第二次:new 本质上也调用了父构造函数
Child.prototype.run = function(){console.log(this.msg +' '+ this.childMsg)}
let child = new Child();
child.run();
child.say();
2. 寄生组合继承
function inheritProperty(Child,Father){
let prototype = Object.create(Father.prototype);
prototype.constructor = Child;
Child.prototype = prototype
}
function Father(){
this.msg = "Hello"
}
Father.prototype.say = function(){console.log(this.msg)}
function Child(){
Father.call(this); // // 第一次:通过 call 调用父构造函数
this.childMsg = 'child';
}
inheritProperty(Child,Father); // 替换 Child.prototype = new Father();
Child.prototype.run = function(){console.log(this.msg +' '+ this.childMsg)}
let child = new Child();
child.run();
child.say();
可以看出寄生组合继承与原型组合继承非常类似,只是有一行被替换了。寄生组合继承与原型组合继承相比,寄生组合继承少调用一次父构造函数。寄生组合继承之所以可以调用一次是因为它引入了一个空函数,将父构造函数的原型对象赋予此空函数,然后再将这个空函数的实例赋予子构造函数的原型对象。其实他也调用的两次函数,只不过第二次调用的是空函数,当然比调用父函数的开销要小了,所以寄生组合继承也被都被普遍认为是最理想的继承实现方式。