萬盛學電腦網

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

JavaScript 模擬類別繼承三大模式:prototype、apply、call+prototype 深度解析

前言

JavaScript 沒有傳統「類別」,透過**原型鏈**模擬繼承。本文詳細比較三種經典模擬繼承模式,分析優缺點與適用場景。

基礎父類別

// 父類別
function ParentClass() {
  this.className = "ParentClass";
  this.auth = "Auth";
  this.version = "V1.0";
  this.parentClassInfo = function() {
    return this.className + "\n" + this.auth + "\n" + this.version;
  };
}

模式一:prototype 原型鏈繼承

// 子類別
function ChildClassByPrototype() {
  this.date = "2013-07-26";
  this.classInfo = function() {
    return this.parentClassInfo() + "\n" + this.date;
  };
}

// 關鍵:子類別 prototype 指向父類別實例
ChildClassByPrototype.prototype = new ParentClass();

// 測試
var cctest1 = new ChildClassByPrototype();
console.log(cctest1.parentClassInfo()); // 繼承自父類
console.log(cctest1.classInfo());       // 子類擴充

原理

JS 尋找 `cctest1.parentClassInfo()` 時:實例無 → 找 `ChildClassByPrototype.prototype`(即 `ParentClass` 實例) → 找到方法 → 執行。

優缺點

優點缺點
簡單直觀;繼承父類原型鏈上所有方法 無法向父類建構函式傳參;父類實例屬性會被所有子類實例共享(引用型別風險)

模式二:apply 借用建構函式

function ChildClassByApply() {
  ParentClass.apply(this, []); // 或 new Array()
  this.date = "2013-07-26";
  this.classInfo = function() {
    return this.parentClassInfo() + "\n" + this.date;
  };
}

// 測試
var cctest2 = new ChildClassByApply();
console.log(cctest2.parentClassInfo()); // 正常
console.log(cctest2 instanceof ParentClass); // false!

原理

`apply` 將 `ParentClass` 的 `this` 綁定到子類實例,複製自有屬性與方法。但**不修改 prototype**,所以 `instanceof` 失效。

優缺點

優點缺點
可傳參給父類建構函式;每個實例擁有獨立屬性副本 無法繼承父類 prototype 上的方法;`instanceof` 判斷失效

模式三:call + prototype 組合繼承(推薦)

function ChildClassByCall() {
  ParentClass.call(this, arguments); // 借用建構函式複製自有屬性
  this.date = "2013-07-26";
  this.classInfo = function() {
    return this.parentClassInfo() + "\n" + this.date;
  };
}
// 關鍵:繼承 prototype 方法
ChildClassByCall.prototype = new ParentClass();
// 修正 constructor 指向(可選但推薦)
ChildClassByCall.prototype.constructor = ChildClassByCall;

// 測試
var cctest3 = new ChildClassByCall();
console.log(cctest3.parentClassInfo()); // 來自 prototype
console.log(cctest3 instanceof ParentClass); // true ✓
console.log(cctest3 instanceof ChildClassByCall); // true ✓

優缺點

優點缺點
同時繼承自有屬性與 prototype 方法;`instanceof` 正常;可傳參 父類建構函式被呼叫兩次(一次在 call,一次在 new ParentClass())

帶參數建構函式的處理

function ParentClass(className, auth, version) {
  this.className = className;
  this.auth = auth;
  this.version = version;
  this.parentClassInfo = function() {
    return this.className + "\n" + this.auth + "\n" + this.version;
  };
}

// apply 版
function ChildByApply(className, auth, version) {
  ParentClass.apply(this, [className, auth, version]);
  // ...
}

// call 版
function ChildByCall(className, auth, version) {
  ParentClass.call(this, className, auth, version); // 直接展開參數
  // ...
}
ChildByCall.prototype = new ParentClass("default", "default", "default"); // 原型鏈用預設值

為什麼 Google Maps API 採用 call + prototype?

因為它同時滿足:

  1. 子類實例擁有獨立自有屬性(避免共享引用型別)
  2. 子類 `instanceof ParentClass === true`(多型檢查正確)
  3. 繼承父類 prototype 上的共享方法(記憶體效率)

現代替代:ES6 Class 語法糖

class Parent {
  constructor(className, auth, version) {
    this.className = className;
    this.auth = auth;
    this.version = version;
  }
  parentClassInfo() {
    return `${this.className}\n${this.auth}\n${this.version}`;
  }
}

class Child extends Parent {
  constructor(className, auth, version, date) {
    super(className, auth, version); // 必須先呼叫 super()
    this.date = date;
  }
  classInfo() {
    return super.parentClassInfo() + "\n" + this.date;
  }
}

總結建議

  • **ES6 環境**:直接用 `class extends`,語意清晰、錯誤少。
  • **舊環境(ES5)**:採用 **組合繼承** 或 **寄生組合繼承**(避免雙重呼叫父建構函式)。
  • 理解底層原型機制,才能在除錯與架構設計時遊刃有餘。
copyright © 萬盛學電腦網 all rights reserved