萬盛學電腦網

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

JavaScript 物件導向繼承模式大全:從原型鏈到 ES6 Class 與組合模式

前言

JavaScript 物件導向的核心是**原型繼承**。ES6 class 只是語法糖,理解底層機制才能靈活應用各種繼承模式。本文整合兩篇原始文章(ID 72057、72058),系統性介紹 5 種主流繼承模式與現代最佳實務。

1. 原型鏈繼承

function Parent(name) { this.name = name; }
Parent.prototype.sayHi = function() { console.log('Hi, ' + this.name); };

function Child(name, age) { this.age = age; }
Child.prototype = new Parent(); // 關鍵:子原型指向父實例
Child.prototype.constructor = Child; // 修正 constructor

const c = new Child('Tom', 10);
c.sayHi(); // Hi, Tom — 但 c.name 為 undefined!
缺點:父建構函數未被呼叫,實例屬性未繼承;原型屬性被所有實例共享(引用型別風險)。

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

function Child(name, age) {
    Parent.call(this, name); // 在子建構函數中呼叫父建構函數
    this.age = age;
}
// 原型不連結,無法繼承父 prototype 方法
優點:解決實例屬性繼承、可傳參。缺點:方法無法複用(每實例一份),父原型方法不可用。

3. 組合繼承(經典模式,ES5 最常用)

function Parent(name) {
    this.name = name;
    this.colors = ['red', 'blue']; // 引用型別測試
}
Parent.prototype.sayHi = 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;

const c1 = new Child('Tom', 10);
const c2 = new Child('Jerry', 8);
c1.colors.push('green');
console.log(c2.colors); // ['red', 'blue', 'green'] — 共享引用!
缺點:父建構函數被呼叫**兩次**(一次在 Child.prototype = new Parent(),一次在 Parent.call(this)),產生兩份實例屬性(原型上一份、實例上一份),記憶體浪費。

4. 原型式繼承 / Object.create (ES5 標準化)

const parent = {
    name: 'Parent',
    greet() { console.log(this.name); }
};

const child = Object.create(parent);
child.name = 'Child';
child.greet(); // Child

// 等同於 Douglas Crockford 的 object(o) 函式
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}
適用於「單一物件繼承另一物件」,無建構函數概念。ES5 標準化為 Object.create()。

5. 寄生組合式繼承(ES5 最佳模式)

function inheritPrototype(Child, Parent) {
    const prototype = Object.create(Parent.prototype); // 建立空物件,原型指向 Parent.prototype
    prototype.constructor = Child;                    // 修正 constructor
    Child.prototype = prototype;                      // 子原型指向該空物件
}

function Parent(name) {
    this.name = name;
    this.colors = ['red', 'blue'];
}
Parent.prototype.sayHi = function() { console.log(this.name); };

function Child(name, age) {
    Parent.call(this, name); // 唯一呼叫父建構函數
    this.age = age;
}

inheritPrototype(Child, Parent); // 取代 Child.prototype = new Parent()

const c1 = new Child('Tom', 10);
const c2 = new Child('Jerry', 8);
c1.colors.push('green');
console.log(c2.colors); // ['red', 'blue'] — 獨立!

優點: 父建構函數只呼叫一次、原型鏈完整、無多餘屬性、引用型別隔離。這是 ES5 環境下最理想的繼承模式。

6. ES6 Class extends(現代標準,語法糖)

class Parent {
    constructor(name) {
        this.name = name;
        this.colors = ['red', 'blue'];
    }
    sayHi() { console.log(this.name); }
}

class Child extends Parent {
    constructor(name, age) {
        super(name); // 必須先呼叫 super()
        this.age = age;
    }
    // 可覆寫方法
    sayHi() {
        super.sayHi();
        console.log('Age:', this.age);
    }
}

const c = new Child('Tom', 10);
c.sayHi(); // Tom \n Age: 10
  • extends 內部實作即為**寄生組合式繼承**。
  • super() 對應 Parent.call(this)。
  • 靜態方法、存取器、私有欄位 (#field) 皆原生支援。

7. 組合模式 / 混入 — 替代繼承的靈活方案

// 混入多個行為
const Flyable = {
    fly() { console.log(this.name + ' flying'); }
};
const Swimmable = {
    swim() { console.log(this.name + ' swimming'); }
};

function Duck(name) { this.name = name; }
Object.assign(Duck.prototype, Flyable, Swimmable);

const d = new Duck('Daffy');
d.fly(); d.swim();
「組合優於繼承」。JS 物件扁平化特性讓混入極為自然,避免深層繼承樹的脆弱性。

模式選擇指南

場景推薦模式
現代專案 (ES6+、Babel/TypeScript)class extends
舊專案維護 (ES5 環境)寄生組合式繼承
單一物件擴展、無建構函數Object.create() / 混入
多重行為複用(飛行、游泳、可序列化)Mixin / 組合
需要多重繼承JS 不支援,改用混入或介面隔離

原始文章代碼修正版(ID 72057 批量實現)

// 修正後的 extend 函式:正確建立原型鏈、支援多重繼承
function extend(Parent, ChildConstructor, childMethods) {
    // 1. 建立中介建構函數
    function Surrogate() {}
    Surrogate.prototype = Parent.prototype;

    // 2. 子建構函數
    function Extended(...args) {
        Parent.apply(this, args);        // 繼承實例屬性
        ChildConstructor.apply(this, args); // 子類初始化
    }
    Extended.prototype = new Surrogate(); // 原型鏈:Extended -> Surrogate -> Parent.prototype
    Extended.prototype.constructor = Extended;

    // 3. 混入子類方法
    Object.assign(Extended.prototype, childMethods);
    return Extended;
}

// 使用
const Person = function(name, age) { this.name = name; this.age = age; };
Person.prototype.showName = function() { console.log(this.name); };

const Worker = extend(Person,
    function(name, age, job) { this.job = job; }, // 子建構函數
    { showJob() { console.log(this.job); } }      // 子方法
);

const w = new Worker('俠客', 24, '工程師');
w.showName(); // 俠客
w.showJob();  // 工程師

理解這些模式的演進脈絡,才能在遺留代碼維護與現代開發中遊刃有餘,寫出健壯且可維護的 JS 物件導向代碼。

copyright © 萬盛學電腦網 all rights reserved