萬盛學電腦網

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

JavaScript 組合模式:建構函式 + 原型鏈 實現繼承與共享方法

前言

「組合模式」結合**建構函式定義實例屬性** + **原型定義共享方法/屬性**,是 ES5 時代最主流的繼承模式,兼顧實例獨立性與記憶體效率。

核心程式碼

function Person(name, age, job) {
  // 實例屬性:每個實例獨擁
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ['Shelby', 'Court']; // 參考型別需在建構函式初始化,避免共享
}

// 共享方法定義在原型
Person.prototype = {
  constructor: Person, // 修正 constructor 指向
  sayName() {
    console.log(this.name);
  },
  sayAge() {
    console.log(this.age);
  }
};

// 使用
const person1 = new Person('Jack', 25, 'Engineer');
const person2 = new Person('Karry', 30, 'Designer');

person1.friends.push('Tom');
console.log(person1.friends); // ['Shelby', 'Court', 'Tom']
console.log(person2.friends); // ['Shelby', 'Court'] (獨立)

console.log(person1.sayName === person2.sayName); // true (共享同一函式)

關鍵點解析

  1. 實例屬性在建構函式:確保每個實例擁有獨立副本,特別是參考型別 (陣列、物件)。
  2. 方法/共享屬性在原型:節省記憶體,所有實例指向同一函式物件。
  3. 重寫 prototype 物件時必須手動設定 `constructor`**,否則 `instanceof` 正常但 `constructor` 指向 `Object`。
  4. 原型鏈查找**:讀取屬性時先找實例 → 再找原型 → 再找 `Object.prototype`。

繼承實作:寄生組合式繼承 (ES5 最佳)

function inheritPrototype(SubType, SuperType) {
  const prototype = Object.create(SuperType.prototype); // 建立超類原型副本
  prototype.constructor = SubType;                      // 修正 constructor
  SubType.prototype = prototype;                        // 指派給子類原型
}

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

function Sub(name, age) {
  Super.call(this, name); // 繼承實例屬性 (借用建構函式)
  this.age = age;
}

inheritPrototype(Sub, Super); // 繼承原型方法

Sub.prototype.sayAge = function() { console.log(this.age); };

const sub = new Sub('Jack', 25);
sub.sayName(); // Jack
sub.sayAge();  // 25
sub.colors.push('green');
console.log(sub.colors); // ['red', 'blue', 'green'] (獨立)

ES6 Class 等價寫法

class Person {
  constructor(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ['Shelby', 'Court'];
  }
  sayName() { console.log(this.name); }
}

class Employee extends Person {
  constructor(name, age, job, employeeId) {
    super(name, age, job);
    this.employeeId = employeeId;
  }
  sayId() { console.log(this.employeeId); }
}

總結

組合模式 (建構函式 + 原型) 是 ES5 物件導向精髓。ES6 `class` 底層即此機制的語法糖。理解「實例屬性在建構函式、共享方法在原型」原則,即能正確設計繼承體系並避免共享參考型別 Bug。

copyright © 萬盛學電腦網 all rights reserved