要在 JavaScript 裡做繼承,方法不止一種,而且每種都有明確的取捨。理解它們的優缺點,才能在真實專案中選對工具。以下依序說明六種模式。
最直觀的做法:把子類型的原型指向父類型的實例。
// 父類型
function SuperType() {
this.name = ['wuyuchang', 'Jack', 'Tim'];
this.property = true;
}
SuperType.prototype.getSuerperValue = function() {
return this.property;
};
// 子類型
function SubType() {
this.test = ['h1', 'h2', 'h3', 'h4'];
this.subproperty = false;
}
// 實現繼承的關鍵步驟
SubType.prototype = new SuperType();
// 給子類型添加方法,一定要在實現繼承之後,
// 否則會被指向父類型實例的賦值覆蓋掉
SubType.prototype.getSubValue = function() {
return this.subproperty;
};
var instance1 = new SubType();
instance1.name.push('wyc');
instance1.test.push('h5');
alert(instance1.getSuerperValue()); // true
alert(instance1.getSubValue()); // false
alert(instance1.name); // wuyuchang,Jack,Tim,wyc
alert(instance1.test); // h1,h2,h3,h4,h5
var instance2 = new SubType();
alert(instance2.name); // wuyuchang,Jack,Tim,wyc ← 被污染了
alert(instance2.test); // h1,h2,h3,h4
兩個致命問題
第一,子類型的原型就是父類型的一個實例,因此父類型上的引用型屬性會被所有子實例共享。上面 instance1 push 了 'wyc',instance2 也看到了——這正是共享原型的副作用。
第二,建立子類型實例時,無法向父類型的構造函數傳遞參數。
因此實務中很少單獨使用原型鏈。
思路是:既然函數只是在特定環境中執行代碼的物件,那就在子類型構造函數裡呼叫父類型構造函數,透過 apply 或 call 改變 this 指向。
function SuperType(name) {
this.name = name;
this.color = ['pink', 'yellow'];
this.property = true;
this.testFun = function() {
alert('https://tools.jb51.net/');
};
}
SuperType.prototype.getSuerperValue = function() {
return this.property;
};
function SubType(name) {
SuperType.call(this, name); // 繼承屬性,並可傳參
this.test = ['h1', 'h2', 'h3', 'h4'];
this.subproperty = false;
}
SubType.prototype.getSubValue = function() {
return this.subproperty;
};
var instance1 = new SubType(['wuyuchang', 'Jack', 'Nick']);
instance1.name.push('hello');
instance1.test.push('h5');
instance1.color.push('blue');
instance1.testFun(); // https://tools.jb51.net/
alert(instance1.name); // wuyuchang,Jack,Nick,hello
// alert(instance1.getSuerperValue()); // error! 原型上的方法拿不到
alert(instance1.test); // h1,h2,h3,h4,h5
alert(instance1.getSubValue()); // false
alert(instance1.color); // pink,yellow,blue
var instance2 = new SubType('wyc');
instance2.testFun();
alert(instance2.color); // pink,yellow ← 互不干擾
這樣解决了引用共享與傳參問題,但新問題出現:父類型原型上定義的方法完全無法繼承,只有構造函數內定義的 testFun 可用。這等同於只用構造函數模式建物件——方法無法復用,每個實例都帶一份函數副本。
把兩者的優點合起來:用原型鏈繼承方法,用構造函數繼承屬性。
function SuperType(name) {
this.name = name;
this.color = ['pink', 'yellow'];
this.property = true;
this.testFun = function() {
alert('https://tools.jb51.net/');
};
}
SuperType.prototype.getSuerperValue = function() {
return this.property;
};
function SubType(name) {
SuperType.call(this, name); // 繼承屬性
this.test = ['h1', 'h2', 'h3', 'h4'];
this.subproperty = false;
}
SubType.prototype = new SuperType(); // 繼承方法
SubType.prototype.getSubValue = function() {
return this.subproperty;
};
var instance1 = new SubType(['wuyuchang', 'Jack', 'Nick']);
instance1.name.push('hello');
instance1.test.push('h5');
instance1.color.push('blue');
instance1.testFun(); // https://tools.jb51.net/
alert(instance1.name); // wuyuchang,Jack,Nick,hello
alert(instance1.getSuerperValue()); // true ← 原型方法也能用了
alert(instance1.test); // h1,h2,h3,h4,h5
alert(instance1.getSubValue()); // false
alert(instance1.color); // pink,yellow,blue
var instance2 = new SubType('wyc');
instance2.testFun();
alert(instance2.name); // wyc
alert(instance2.getSuerperValue()); // true
alert(instance2.color); // pink,yellow ← 互不干擾
這是最常用的繼承方式,但它有個明顯浪費:SubType.prototype = new SuperType() 這行會執行一次父構造函數,而 SuperType.call(this, name) 又執行一次,父構造函數被呼叫了兩次。第一次產生的屬性立刻被第二次的覆蓋掉,白做工。
不建立真正的構造函數,而是借助原型「基於既有物件產生新物件」的能力:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
使用示例:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var person = {
name : 'wuyuchang',
friends : ['wyc', 'Nicholas', 'Tim']
};
var anotherPerson = object(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Bob');
var anotherPerson2 = object(person);
anotherPerson2.name = 'Jack';
anotherPerson2.friends.push('Rose');
alert(person.friends); // wyc,Nicholas,Tim,Bob,Rose ← 又是共享引用
本質上與原型鏈是同一個問題的兩種外衣,引用共享依舊存在。
在原型式繼承的基礎上,於返回前對克隆體做增補:
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 : 'wuyuchang', friends : ['wyc', 'Nicholas', 'Rose'] };
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
使用起來方便,但方法只能寫在每個克隆體上,復用性依舊不佳。
它精準解決了組合繼承的雙呼叫問題:屬性用構造函數繼承,方法則用「複製父類型原型」的方式繼承,完全不執行父類型的構造函數。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
/* 寄生組合式繼承 */
function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype); // 建立副本
prototype.constructor = subType; // 修正 constructor 指向
subType.prototype = prototype;
}
使用時,只需把組合模式中的 SubType.prototype = new SuperType(); 換成:
inheritPrototype(SubType, SuperType);
它的優勢
· 父類型構造函數只被呼叫一次(在 SuperType.call 那裡),避免了建立不必要的屬性。
· 原型鏈保持完整,instanceof 與 isPrototypeOf() 都能正常運作。
· 手動設定 constructor,讓型別識別結果正確。
這也是目前公認最理想的繼承方式,YUI 等庫採用的正是這個模式。
日常開發直接用組合繼承即可,理解成本最低;若在意效能或追求語意精確,改用寄生組合式。至於 ES6 的 class / extends,語法糖背後正是寄生組合式的最佳實踐,並自動處理 super 呼叫與 constructor 指向,新專案沒有理由再手寫上述程式碼。
本文以《JavaScript 高級程序設計(第 3 版)》為基礎,示例經過改寫並補充註解以便理解。若對 JS 繼承另有見解,歡迎交流。