JavaScript 沒有類,透過 prototype 鏈實現繼承。核心矛盾在於:原型鏈共享引用型別屬性會互相影響,而借用建構函數又無法復用原型方法。本文梳理六大繼承模式演進脈絡,鎖定最佳實踐。
function Parent() { this.name = 'Mike'; }
function Child() { this.age = 12; }
Child.prototype = new Parent(); // 關鍵:子類原型指向父類實例
var test = new Child();
console.log(test.name); // 'Mike'(來自原型鏈)
缺點:Parent 的引用屬性(陣列/物件)被所有子實例共享;無法向父類傳參。
function Parent(age) {
this.name = ['Mike', 'Jack'];
this.age = age;
}
function Child(age) {
Parent.call(this, age); // 在子類建構函數中呼叫父類
}
var test = new Child(21);
test.name.push('Bill'); // 僅影響 test 實例
優點:解決引用共享、可傳參。缺點:方法無法復用(每實例各有一份)。
function Parent(age) {
this.name = ['Mike', 'Jack'];
this.age = age;
}
Parent.prototype.run = function() { return this.name + ' are ' + this.age; };
function Child(age) {
Parent.call(this, age); // 第二次呼叫 Parent
}
Child.prototype = new Parent(); // 第一次呼叫 Parent
// Child.prototype.constructor = Child; // 修正 constructor
var test = new Child(21);
console.log(test.run()); // 方法來自原型,屬性來自建構函數
缺點:父類建構函數被呼叫兩次(一次在 Child.prototype = new Parent(),一次在 Parent.call(this)),產生兩份實例屬性(原型上一份、實例上一份)。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var box = { name: 'Trigkit4', arr: ['brother', 'sister'] };
var b1 = object(box);
var b2 = object(box);
b1.arr.push('parents');
console.log(b2.arr); // ['brother', 'sister', 'parents'] ── 仍共享引用
本質是 Object.create() 的 Polyfill,適用於無建構函數、單純物件擴充場景。
function create(o) {
var f = object(o); // 原型式繼承
f.run = function() { return this.arr; }; // 增強
return f;
}
結合工廠模式,封裝建立過程,但同樣有引用共享問題。
function inheritPrototype(Sub, Sup) {
var prototype = Object.create(Sup.prototype); // 只繼承原型,不呼叫建構函數
prototype.constructor = Sub;
Sub.prototype = prototype;
}
function Parent(name) {
this.name = name;
this.arr = ['brother', 'sister', 'parents'];
}
Parent.prototype.run = function() { return this.name; };
function Child(name, age) {
Parent.call(this, name); // 只呼叫一次父類建構函數
this.age = age;
}
inheritPrototype(Parent, Child); // 核心:只繼承原型
var test1 = new Child('Trigkit4', 21);
test1.arr.push('nephew');
var test2 = new Child('Jack', 22);
console.log(test1.arr); // 獨立
console.log(test2.arr); // 獨立
console.log(test1.run()); // 方法共享
優點:父類建構函數只呼叫一次、原型鏈乾淨、instanceof 與 isPrototypeOf 正常運作。
| API | 用途 | 備註 |
|---|---|---|
Object.create(proto) | 建立指定原型的新物件 | ES5,替代 new F() |
Sup.call(this, args) | 借用父類建構函數初始化實例屬性 | 解決引用共享、傳參 |
Sub.prototype = Object.create(Sup.prototype) | 繼承父類原型方法 | 不產生父類實例屬性 |
Sub.prototype.constructor = Sub | 修正 constructor 指向 | 維持 instanceof 語義 |
function foo() { console.log(this.fruit); }
var fruit = 'apple';
var pack = { fruit: 'orange' };
foo.call(window); // 'apple'(this 指向 window)
foo.call(pack); // 'orange'(this 指向 pack)
foo.apply(pack, []); // 同 call,參數為陣列
從原型鏈 → 借用建構函數 → 組合 → 寄生組合,每一步都在解決上一步的痛點。現代專案請直接採用 寄生組合式繼承(或 ES6 class extends 語法糖),並理解其背後原型鏈機制,才能在除錯與擴充時遊刃有餘。