JS 繼承歷經多次演進。本文系統梳理 apply/call 借用建構器、原型鏈繼承、組合繼承、寄生組合繼承、ES6 class extends 的原理、優缺點與適用場景,並給出現代最佳實踐。
function Parent(name) {
this.name = name;
this.say = () => console.log(this.name); // 實例方法,每個實例獨佔
}
function Child(name, age) {
Parent.call(this, name); // 或 Parent.apply(this, [name])
this.age = age;
}
const c = new Child('Tom', 10);
c.say(); // 'Tom'
缺點:父構造函數中的引用類型屬性會被共享;方法定義在構造函數內,無法複用,浪費記憶體。
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
缺點:無法向父構造函數傳參;原型上的引用類型屬性被所有實例共享(修改會互相影響)。
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 = Object.create(Parent.prototype); // 第一次調用 Parent
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() { console.log(this.age); };
缺點:父構造函數被調用兩次,產生兩份實例屬性(一份在 Child.prototype 上,一份在實例上),雖然實例屬性覆蓋了原型屬性,但有性能浪費。
function inheritPrototype(Child, Parent) {
const prototype = Object.create(Parent.prototype); // 創建中間對象
prototype.constructor = Child;
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); // 僅調用一次
this.age = age;
}
inheritPrototype(Child, Parent);
Child.prototype.sayAge = function() { console.log(this.age); };
優點:只調用一次父構造函數、原型鏈純淨、instanceof/isPrototypeOf 正常。
class Parent {
constructor(name) { this.name = name; this.colors = ['red']; }
sayName() { console.log(this.name); }
}
class Child extends Parent {
constructor(name, age) {
super(name); // 必須先調用 super()
this.age = age;
}
sayAge() { console.log(this.age); }
}
優點:語法清晰、靜態分析友好、支援 super 調用父方法、原生 extends 可繼承內建類別(Array, Error, Map 等)。
class extends**;舊代碼維護時理解寄生組合繼承原理即可。