思路與寄生建構函式、工廠模式類似:寫一個專門封裝繼承流程的函式,在內部以某種方式增強物件,最後把它回傳。
function createAnother(original){
var clone = Object.create(original); // 以原物件為原型建立新物件
clone.sayHi = function(){ // 以某種方式增強這個物件
alert("Hi");
};
return clone; // 回傳
}
var person = {
name: "Bob",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
createAnother 接收一個參數,也就是作為新物件基礎的物件。anotherPerson 是基於 person 建立的,因此它具備 person 的所有屬性與方法,同時擁有自己的 sayHi()。
這種模式的優點是簡單、不必涉及型別;缺點也很明顯:方法只能寫在每個新物件上,無法共用,記憶體使用效率不佳。實務上它比較適合用來「以某個物件為模板,快速做出外觀相似但行為略有差異的物件」。
組合式繼承是最常用的模式,但它有個結構性問題:無論在什麼情況下,建構函式都會被呼叫兩次——一次在建立子類型原型時,另一次在子類型建構函式內部。
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name); // 第二次呼叫 SuperType()
this.age = age;
}
SubType.prototype = new SuperType(); // 第一次呼叫 SuperType()
SubType.prototype.sayAge = function(){
alert(this.age);
};


推一遍流程就能看清問題所在。
第一次呼叫 SuperType 時(為了指定 SubType.prototype),SubType.prototype 上取得了 name 與 colors 兩個屬性。它們本是 SuperType 的實例屬性,如今卻躺在子類型的原型上。
等到 new SubType() 時,SubType 建構函式內部又呼叫了一次 SuperType.call(this, name),於是在新物件上再產生一組 name 與 colors。這組新的實例屬性,就把原型上的同名屬性遮蔽掉了。
結果就是:那兩個掛在原型上的屬性永遠用不到,純屬浪費。寄生組合式繼承正是為了解決這個問題而生。它的做法是:
function inheritPrototype(subType, superType){
var protoType = Object.create(superType.prototype); // 建立超類型原型的副本
protoType.constructor = subType; // 增強:補回 constructor
subType.prototype = protoType; // 指定給子類型
}
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name); // 只呼叫這一次
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance = new SubType("Bob", 18);
instance.sayName();
instance.sayAge();
inheritPrototype 接收子類型與超類型兩個建構函式,內部三步:
Object.create(superType.prototype) 建立超類型原型的副本,作為橋接,避免直接呼叫 SuperType;constructor 屬性——因為重新指定 prototype 會失去預設的 constructor,不補的話 instance.constructor 會指向 SuperType 而非 SubType;如此一來 SuperType 只被呼叫了一次,同時 instanceof 與 isPrototypeOf() 也都能正常運作,是公認最理想的繼承方式。
如果環境允許,上面這整套手工打造都能用一行 class 語法取代,底層做的正是同樣的事:
class SuperType {
constructor(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
sayName() {
alert(this.name);
}
}
class SubType extends SuperType {
constructor(name, age) {
super(name); // 對應 SuperType.call(this, name)
this.age = age;
}
sayAge() {
alert(this.age);
}
}
var instance = new SubType("Bob", 18);
console.log(instance instanceof SubType); // true
console.log(instance instanceof SuperType); // true
extends 自動處理好原型鏈與 constructor,super() 必須在存取 this 之前呼叫。理解手寫版的每一步,才能明白 class 語法糖背後究竟發生了什麼——這在 debug 複雜的 this 問題時尤其有用。