在ES6之前,JavaScript中的繼承是通過原型鏈來實現的;下面對此進行分析:
一、原型鏈
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
function SubType() {
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new SubType();
console.log(instance.getSuperValue());//true
2、創建子類型的實例時,沒有辦法在不影響所有實例的情況下向超類型的構造函數傳遞參數;
基於以上缺點,實際應用中很少單獨使用原型鏈,爲解決這一問題,開發人員又提出一種借用構造函數的技術
二、借用構造函數
function SuperType(name) {
this.name = name;
this.friends = ['Alice'];
}
function SubType() {
SuperType.call(this, 'Jack');
this.age = 29;
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.friends.push('Bob');
console.log(instance1.name + ' ' + instance1.age);//Jack 29
console.log(instance2.name + ' ' + instance2.age);//Jack 29
console.log(instance1.friends);//["Alice", "Bob"]
console.log(instance2.friends);//["Alice"]
2、和原型鏈方式相比,借用構造函數的最大的優勢是可以向父類傳遞參數(代碼中的name參數);