ES6 的 class 出現之前,JavaScript 的繼承全靠手動安排原型鏈與建構函式。這篇文章整理四種主要做法,並說明為什麼寄生組合式被公認是最理想的方案。
組合繼承又叫偽經典繼承,做法是將原型鏈與借用建構函式兩種技術結合起來。
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;
}
SubType.prototype = new SuperType(); // 原型鏈
SubType.prototype.sayAge = function () {
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); // red,blue,green,black
instance1.sayName(); // Nicholas
instance1.sayAge(); // 29
var instance2 = new SubType("Greg", 27);
alert(instance2.colors); // red,blue,green
instance2.sayName(); // Greg
instance2.sayAge(); // 27
這個寫法同時解決了兩個問題:原型鏈無法傳遞參數,而單純借用建構函式又無法共用方法。組合繼承因此成為最常被人使用的模式。
可以在不必預先定義建構函式的情況下實作繼承,本質是對給定物件做一次淺複製,而複製出來的副本還可以再進一步改造。
function object(o) {
function F() {}
F.prototype = o;
return new F;
}
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var antherPerson = object(person);
antherPerson.name = "Greg";
antherPerson.friends.push("Rob");
var anotherPerson = object(person);
anotherPerson.name = "Linda";
anotherPerson.friends.push("Barbie");
alert(person.friends); // Shelby,Court,Van,Rob,Barbie
注意最後一行:person.friends 被兩個副本共同改動了。這是因為淺複製只複製參照,陣列仍然是同一個。這也是原型式繼承最大的限制。
與原型式繼承非常相似,同樣是基於某個物件建立新物件,接著增強它,最後回傳。它的價值在於可以與組合繼承搭配使用,解決組合繼承中「每次建立實例都要呼叫兩次超類型建構函式」的低效率問題。
function object(o) {
function F() {}
F.prototype = o;
return new F;
}
function createAnother(original) {
var clone = object(original);
clone.sayHi = function () {
alert("Hi");
};
return clone;
}
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
缺點是新增的方法無法共用,每個副本都有一份自己的函式,記憶體使用效率不佳。
它把寄生式與組合式的優點結合起來,被普遍認為是實作參照型別繼承最有效的方式。
// 繼承原型
function extend(subType, superType) {
function F() {}
F.prototype = superType.prototype;
var prototype = new F;
prototype.constructor = subType;
subType.prototype = prototype;
}
// 超類方法
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
return this.name;
};
// 子類方法
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
// 繼承超類的原型
extend(SubType, SuperType);
SubType.prototype.sayAge = function () {
return this.age;
};
var instance1 = new SubType("Shelby");
var instance2 = new SubType("Court", 28);
instance1.colors.push('black');
alert(instance1.colors); // red,blue,green,black
alert(instance2.colors); // red,blue,green
alert(instance1 instanceof SubType); // true
alert(instance1 instanceof SuperType); // true
它的高效率體現在兩點:SuperType 建構函式只被呼叫了一次,因此不必為了建立原型鏈而多跑一輪;同時也避免了在 SubType.prototype 上產生不必要的多餘屬性。此外,原型鏈結構依然完整,instanceof 與 isPrototypeOf() 都能正常運作。
如果只是想快速把功能做出來,組合繼承足夠用,也最容易理解。若追求效能與結構的嚴謹,寄生組合式是更理想的選擇——事實上,ES6 的 class ... extends 在語法糖背後做的就是這件事。原型式與寄生式繼承則更適合用於「以現成物件為模板快速產生相似物件」的場景,但要特別小心參照型別屬性被所有副本共享的問題。