JS 透過原型鏈實現繼承,但單純 `Child.prototype = new Parent()` 存在兩大缺陷:
function A() {}
A.prototype.a1 = function(){};
function B() {}
B.prototype = new A(); // 1. 執行 A(),2. B.prototype.constructor === A
B.prototype.b1 = function(){};
var b = new B();
console.log(b.constructor === A); // true ❌
console.log(b.constructor === B); // false ❌
function A(s1, s2) {
this.total = s1.length + s2.length;
}
function B(s1, s2) {
// 無法將 s1,s2 傳給 A
}
B.prototype = new A(); // 報錯:s1 is undefined
function A(s1, s2) {
this.total = s1.length + s2.length;
}
A.prototype.a1 = function(){};
function B(s1, s2) {
// 1. 借用建構函式傳參(類似 super())
A.apply(this, arguments);
// 此處 this.total 已正確初始化
}
// 2. 原型鏈繼承方法(不執行父建構函式)
for (var m in A.prototype) {
if (!B.prototype[m]) { // 子類優先,不覆蓋同名方法
B.prototype[m] = A.prototype[m];
}
}
B.prototype.constructor = B; // 修正 constructor
B.prototype.b1 = function(){};
// 測試
var b = new B('ab', '123');
console.log(b.total); // 5
console.log(b.constructor === B); // true
console.log(b instanceof A); // true
console.log(b instanceof B); // true
class A {
constructor(s1, s2) {
this.total = s1.length + s2.length;
}
a1() {}
}
class B extends A {
constructor(s1, s2) {
super(s1, s2); // 自動呼叫父建構函式並傳參
}
b1() {}
}
const b = new B('ab', '123');
console.log(b.total); // 5
console.log(b instanceof A); // true
Class 底層仍是原型繼承,但解決了所有上述痛點,且語法清晰、支援 `super`、靜態方法、私有欄位(`#field`)等進階特性。