萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 繼承模式:解決無參數與有參數建構函式的原型鏈問題

JS 透過原型鏈實現繼承,但單純 `Child.prototype = new Parent()` 存在兩大缺陷:

  1. 過早執行父建構函式,且無法傳參
  2. 導致 `child.constructor === Parent`,破壞 `instanceof` 語意

問題重現

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

現代化寫法(ES2015 Class)

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`)等進階特性。

建議

  • 新專案**直接使用 Class**
  • 舊代碼維護時,採用「借用建構函式 + 原型拷貝 + 修正 constructor」模式
  • 避免多重繼承(JS 單繼承),組合優於繼承
copyright © 萬盛學電腦網 all rights reserved