JavaScript 作為基於原型的語言,繼承實現方式多樣且易混淆。本文以「父類 Person → 子類 Student」為例,詳細對比三種主流繼承模式的原理、優缺點與記憶體影響,並推薦業界標準的寄生組合繼承作為最佳實踐。
// 父類
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log('Hello, I am ' + this.name);
};
// 子類
function Student(name, sex) {
// 1. 借用建構函式繼承屬性(關鍵步驟)
Person.call(this, name); // 或 Person.apply(this, arguments)
this.sex = sex;
}
Student.prototype = Person.prototype; // 直接指向父類 prototype
Student.prototype.constructor = Student; // 修正 constructor 指向
instanceof Person 為 true。Student.prototype.newMethod = ... 會影響 Person.prototype。// 驗證污染
Student.prototype.add = function () { alert('add'); };
Person.prototype.add(); // 彈出 'add' —— 父類被污染!
Student.prototype = new Person(); // 子類 prototype 指向父類實例
Student.prototype.constructor = Student; // 修正 constructor
Person.call(this, args))。instanceof Person 為 true。function Student(name, sex) {
Person.call(this, name); // 第二次呼叫:建立實例屬性
this.sex = sex;
}
Student.prototype = new Person(); // 第一次呼叫:建立 prototype 鏈
Student.prototype.constructor = Student;
instanceof 正常。// 1. 建立中介空函式
var F = function () {};
F.prototype = Person.prototype;
// 2. 子類 prototype 指向中介實例
Student.prototype = new F();
// 3. 修正 constructor
Student.prototype.constructor = Student;
// 4. 子類建構函式
function Student(name, sex) {
Person.call(this, name); // 僅呼叫一次,建立實例屬性
this.sex = sex;
}
Student.prototype.__proto__ === Person.prototype。instanceof Person、instanceof Student 均為 true。function inherit(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype; // 便於呼叫父類方法
}
// 使用
inherit(Student, Person);
Student.prototype.study = function () { console.log(this.name + ' studying'); };
class Person {
constructor(name) { this.name = name; }
sayHello() { console.log(`Hello, I'm ${this.name}`); }
}
class Student extends Person {
constructor(name, sex) {
super(name); // 必須先呼叫 super()
this.sex = sex;
}
study() { console.log(`${this.name} studying`); }
}
注意:ES6 class 只是語法糖,底層原型機制未變。理解原型繼承原理對除錯、效能調優、庫開發至關重要。
| 場景 | 推薦模式 | 理由 |
|---|---|---|
| 現代專案(ES6+ 環境) | class extends | 語法清晰、標準化、工具鏈支援完善 |
| 舊專案維護(ES5 環境) | 寄生組合繼承 | 效能最優、無副作用、業界標準 |
| 極簡原型共享、無實例屬性 | 原型鏈繼承 | 記憶體最省,但極少適用場景 |
| 需要多重繼承/混入 | Object.assign / Mixin 模式 | JS 單繼承限制,用組合替代繼承 |
Child.prototype.constructor = Child。深入理解原型繼承機制,是進階 JavaScript 開發者的必修課。建議動手在 Console 執行各模式程式碼,觀察 __proto__、prototype、constructor 關係圖,建立直觀心智模型。