萬盛學電腦網

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

JavaScript 面向對象繼承模式實戰:原型鏈組合繼承與 ES6 Class Extends 深度解析

JS 繼承是面試高頻考點,也是構建可復用組件庫的基石。本文從 ES5 經典**組合繼承**(構造函數借用 + 原型鏈)講起,對比 Object.create、寄生組合、ES6 class extends、ES2022 class fields 等演進路線,給出生產級推薦模式。

ES5 組合繼承 (經典面試標準答案)

function Parent(age, name) {
    this.age = age;
    this.name = name;
}
Parent.prototype.show = function() {
    console.log('父級方法:', this.name, this.age);
};

function Child(age, name, job) {
    // 1. 借用構造函數繼承實例屬性 (解決引用類型共享問題)
    Parent.call(this, age, name); // 或 Parent.apply(this, arguments)
    // 2. 子類自身屬性
    this.job = job;
}

// 3. 原型鏈繼承方法
// 關鍵:Child.prototype = Object.create(Parent.prototype); // ES5 標準寫法
// 老式寫法:for-in 循環複製屬性 (不推薦,無法繼承不可枚舉屬性)
(function() {
    for (var i in Parent.prototype) {
        Child.prototype[i] = Parent.prototype[i];
    }
    Child.prototype.constructor = Child; // 修正 constructor 指向
})();

// 測試
var parent = new Parent(14, '俠客行');
var child = new Child(15, '狼俠', '俠客');
child.show(); // "父級方法: 狼俠 15"
console.log(child instanceof Parent); // true
console.log(child instanceof Child);  // true

ES5 寄生組合繼承 (最優 ES5 方案)

function inheritPrototype(Sub, Sup) {
    var prototype = Object.create(Sup.prototype); // 創建超類原型副本
    prototype.constructor = Sub;                 // 修正 constructor
    Sub.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); };

var c = new Child('Jack', 20);
c.sayName(); // Jack
c.sayAge();  // 20
c.colors.push('blue');
console.log(c.colors); // ['red', 'blue'] (獨立副本)

ES6 Class Extends (現代標準,語法糖)

class Parent {
    constructor(age, name) {
        this.age = age;
        this.name = name;
    }
    show() { console.log('父級方法:', this.name, this.age); }
}

class Child extends Parent {
    constructor(age, name, job) {
        super(age, name); // 必須先調用 super(),才能使用 this
        this.job = job;
    }
    // 方法覆寫
    show() {
        super.show(); // 調用父類方法
        console.log('子類擴展, job:', this.job);
    }
}

const child = new Child(15, '狼俠', '俠客');
child.show();
// 父級方法: 狼俠 15
// 子類擴展, job: 俠客

ES2022 Class Fields (Stage 3, 現代瀏覽器已全面支援)

class Parent {
    #privateField = 'secret'; // 私有字段
    static staticProp = 'static';
    
    constructor(name) {
        this.name = name;
    }
}

class Child extends Parent {
    #childSecret = 'child-secret';
    job = 'developer'; // 實例公共字段 (無需 constructor 賦值)
    static childStatic = 'child-static';
    
    constructor(name, job) {
        super(name);
        if (job) this.job = job;
    }
    
    print() {
        console.log(this.name, this.job, this.#childSecret);
        // console.log(this.#privateField); // 錯誤:私有字段不可繼承訪問
    }
}

繼承模式選型決策樹

場景推薦模式理由
現代項目 (ES2015+)class extends + Class Fields語法清晰、原生支援、靜態分析友好、Tree-shaking 友好
需兼容 IE11 (無 Babel)寄生組合繼承ES5 最高效、最標準,避免兩次調用父構造函數
極簡庫/無構建工具Object.create + 工廠函數無 this 綁定困惑、組合優於繼承
多重繼承/混入Object.assign / Mixin 函數JS 單繼承,組合混入替代多重繼承

核心原理總結

  1. 實例屬性:構造函數中 this.xxx 定義,**每個實例獨擁**。繼承時必須 Parent.call(this, ...) 或 super(...) 重新初始化,否則引用類型屬性會被所有實例共享。
  2. 原型方法:定義在 Parent.prototype 上,**所有實例共享**。繼承時建立原型鏈:Child.prototype.__proto__ === Parent.prototype。
  3. constructor 指向:覆寫 prototype 後必須手動修正 Child.prototype.constructor = Child,否則 instanceof 判斷錯誤。
  4. 靜態成員:掛在構造函數/類本身上,extends 會繼承靜態方法 (ES6 特有),Object.create 不會。

深入理解原型鏈機制,能寫出高性能、低內存、易維護的面向對象代碼,也是通過高級前端面試的核心關卡。

copyright © 萬盛學電腦網 all rights reserved