萬盛學電腦網

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

JavaScript 繼承模式全解析:從原型鏈到 ES6 Class 的 9 種實現方式

前言:為什麼 JS 繼承這麼多花樣?

JavaScript 是 基於原型 的語言,沒有類的概念 (ES6 Class 只是語法糖)。這賦予了極大的靈活性,但也導致繼承模式百花齊放。理解各模式優劣,才能根據場景選擇最適合的方案。

核心概念速查

  • [[Prototype]] (Chrome 顯示為 __proto__):對象內部指向原型的隱藏屬性
  • prototype:函數 才有的屬性,指向其構造出的實例的原型
  • constructor:原型上的屬性,指回構造函數
  • 原型鏈查找:自身 → __proto__ → __proto__.__proto__ → ... → null

9 種繼承模式深度解析

1. 原型鏈繼承 (最基礎)

function 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'] ❌ 引用類型共享問題

缺點:引用類型屬性被所有實例共享;無法向父構造函數傳參。

2. 借用構造函數 (經典繼承)

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 ✅ 支援傳參

缺點:方法定義在構造函數內,每個實例都會創建一份函數副本,浪費記憶體;無法繼承父原型上的方法。

3. 組合繼承 (最常用、最經典)

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() 被調用兩次,產生兩份屬性 (實例屬性 + 原型屬性同名覆蓋)

4. 原型式繼承 (Douglas Crockford)

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()。

5. 寄生式繼承

function createAnother(original) {
  const clone = object(original); // 原型式繼承
  clone.sayHi = function() { console.log('hi'); }; // 增強
  return clone;
}

同樣無法解決引用共享,且函數難以複用。

6. 寄生組合式繼承 (最佳實踐、ES6 前標準)

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、引用類型隔離。

7. ES6 Class extends (現代標準)

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); }
}

本質:語法糖,編譯後相當於寄生組合式繼承。現代專案首選。

8. Mixin 混入 (多重繼承替代方案)

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);

解決單繼承限制,組合優於繼承。

9. 物件組合 (無繼承,純組合)

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 / 原型式無構造函數
高效能大量實例借用構造函數 + 原型方法避免原型鏈查找

避坑指南

  1. 忘記 Child.prototype.constructor = Child:導致 instanceof、.constructor.name 異常
  2. 箭頭函數作為原型方法:Child.prototype.say = () => {} 綁定詞法 this,失去動態綁定
  3. 修改內建原型:Array.prototype.myMethod = ... 污染全域,嚴禁
  4. 循環引用:A 繼承 B,B 又繼承 A,導致棧溢出

總結

JavaScript 繼承的本質是 原型鏈委派。從原型鏈繼承 → 組合繼承 → 寄生組合式 → ES6 Class,是對「如何高效共享方法、隔離狀態」的不斷優化。現代開發請直接使用 class extends,理解其底層機制即可應對邊界情況。

copyright © 萬盛學電腦網 all rights reserved