JavaScript 是 基於原型 的語言,沒有類的概念 (ES6 Class 只是語法糖)。這賦予了極大的靈活性,但也導致繼承模式百花齊放。理解各模式優劣,才能根據場景選擇最適合的方案。
[[Prototype]] (Chrome 顯示為 __proto__):對象內部指向原型的隱藏屬性prototype:函數 才有的屬性,指向其構造出的實例的原型constructor:原型上的屬性,指回構造函數__proto__ → __proto__.__proto__ → ... → nullfunction Parent() { this.colors = ['red', 'blue']; }
function Child() {}
Child.prototype = new Parent(); // 核心:子原型指向父實例
Child.prototype.constructor = Child; // 修正 constructor
const child1 = new Child();
child1.colors.push('green');
const child2 = new Child();
console.log(child2.colors); // ['red', 'blue', 'green'] ❌ 引用類型共享問題
缺點:引用類型屬性被所有實例共享;無法向父構造函數傳參。
function Parent(name) {
this.name = name;
this.colors = ['red'];
}
function Child(name, age) {
Parent.call(this, name); // 在子構造函數中調用父構造函數
this.age = age;
}
const child1 = new Child('Alice', 18);
child1.colors.push('blue');
const child2 = new Child('Bob', 20);
console.log(child1.colors); // ['red', 'blue']
console.log(child2.colors); // ['red'] ✅ 解決引用共享
console.log(child1.name, child1.age); // Alice 18 ✅ 支援傳參
缺點:方法定義在構造函數內,每個實例都會創建一份函數副本,浪費記憶體;無法繼承父原型上的方法。
function Parent(name) {
this.name = name;
this.colors = ['red'];
}
Parent.prototype.sayName = function() { console.log(this.name); };
function Child(name, age) {
Parent.call(this, name); // 第二次調用 Parent()
this.age = age;
}
Child.prototype = new Parent(); // 第一次調用 Parent()
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() { console.log(this.age); };
// 問題:Parent() 被調用兩次,產生兩份屬性 (實例屬性 + 原型屬性同名覆蓋)
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
const person = { name: 'Nicholas', friends: ['Shelby', 'Court'] };
const anotherPerson = object(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Rob');
console.log(person.friends); // ['Shelby', 'Court', 'Rob'] ❌ 仍有引用共享
ES5 标准化為 Object.create()。
function createAnother(original) {
const clone = object(original); // 原型式繼承
clone.sayHi = function() { console.log('hi'); }; // 增強
return clone;
}
同樣無法解決引用共享,且函數難以複用。
function inheritPrototype(Child, Parent) {
const prototype = Object.create(Parent.prototype); // 創建中間對象
prototype.constructor = Child; // 修正 constructor
Child.prototype = prototype; // 賦值
}
function Parent(name) {
this.name = name;
this.colors = ['red'];
}
Parent.prototype.sayName = function() { console.log(this.name); };
function Child(name, age) {
Parent.call(this, name); // 只調用一次 Parent()
this.age = age;
}
inheritPrototype(Child, Parent);
Child.prototype.sayAge = function() { console.log(this.age); };
優點:只調用一次父構造函數、原型鏈純淨、支援 instanceof、引用類型隔離。
class Parent {
constructor(name) { this.name = name; }
sayName() { console.log(this.name); }
}
class Child extends Parent {
constructor(name, age) {
super(name); // 必須先調用 super()
this.age = age;
}
sayAge() { console.log(this.age); }
}
本質:語法糖,編譯後相當於寄生組合式繼承。現代專案首選。
const SayMixin = {
sayHi() { console.log(`Hi, I'm ${this.name}`); }
};
const WalkMixin = {
walk() { console.log(`${this.name} is walking`); }
};
class Person {
constructor(name) { this.name = name; }
}
Object.assign(Person.prototype, SayMixin, WalkMixin);
解決單繼承限制,組合優於繼承。
const personProto = {
init(name) { this.name = name; return this; },
sayName() { console.log(this.name); }
};
const child = Object.create(personProto).init('Alice');
// 或工廠函數
function createChild(name, age) {
return Object.assign(Object.create(personProto), { age }).init(name);
}
| 場景 | 推薦模式 | 關鍵詞 |
|---|---|---|
| 現代專案、團隊協作 | ES6 Class extends | 標準、可讀、工具鏈支援 |
| 舊瀏覽器相容、庫開發 | 寄生組合式繼承 | 效能、標準化前最佳 |
| 無狀態行為複用 | Mixin / Object.assign | 組合優於繼承 |
| 動態物件擴展 | Object.create / 原型式 | 無構造函數 |
| 高效能大量實例 | 借用構造函數 + 原型方法 | 避免原型鏈查找 |
Child.prototype.constructor = Child:導致 instanceof、.constructor.name 異常Child.prototype.say = () => {} 綁定詞法 this,失去動態綁定Array.prototype.myMethod = ... 污染全域,嚴禁JavaScript 繼承的本質是 原型鏈委派。從原型鏈繼承 → 組合繼承 → 寄生組合式 → ES6 Class,是對「如何高效共享方法、隔離狀態」的不斷優化。現代開發請直接使用 class extends,理解其底層機制即可應對邊界情況。