萬盛學電腦網

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

JavaScript 代碼復用模式全解析:從類式繼承到組合/寄生/原型式繼承

核心原則

「優先使用對象組合,而非類繼承」 —— 《設計模式》GoF

JS 無類,對象是動態鍵值對,復用靈活多樣。

一、類式繼承模式 (模擬類語法)

1. 原型鏈繼承

function Parent(name) {
  this.name = name || 'Allen';
}
Parent.prototype.say = function() { return this.name; };

function Child(name) {
  this.name = name;
}

// 關鍵:子原型指向父實例
Child.prototype = new Parent();
// 修正 constructor
Child.prototype.constructor = Child;

var kid = new Child('Bob');
kid.say(); // "Bob" (實例屬性遮蔽原型)
kid.constructor === Child; // true

缺點:父實例屬性成為子原型屬性 → 所有子實例共享引用類型屬性 (數組/對象)。

2. 構造函數借用 (call/apply)

function Child(name, age) {
  Parent.call(this, name); // 在子實例上執行父構造函數
  this.age = age;
}
// 缺點:方法無法復用 (每個實例創建新函數)、無法繼承父原型方法

3. 組合繼承 (經典最常用,ES5 標準)

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue']; // 實例屬性
}
Parent.prototype.say = function() { return this.name; };

function Child(name, age) {
  Parent.call(this, name); // 第一次調用:繼承實例屬性
  this.age = age;
}

// 寄生組合式:不創建父實例,只繼承原型
Child.prototype = Object.create(Parent.prototype); // 第二次調用:繼承原型方法
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() { return this.age; };

var child = new Child('Bob', 18);
child.say();    // "Bob" (來自原型)
child.sayAge(); // 18
child.colors.push('green'); // 只影響自身實例

二、原型式繼承 (無構造函數,純對象)

Object.create(proto, [descriptors]) (ES5 標準)

var parent = {
  name: 'Jack',
  greet: function() { console.log('Hi, ' + this.name); }
};

var child = Object.create(parent);
child.name = 'Tom'; // 遮蔽
child.greet(); // "Hi, Tom"

// 繼承構造函數原型 (不調用構造函數)
function Person() { this.name = 'trigkit4'; }
Person.prototype.getName = function() { return this.name; };

var obj = new Person();
var kid = Object.create(obj);        // 繼承實例 (含實例屬性 + 原型方法)
var kid2 = Object.create(Person.prototype); // 僅繼承原型方法
console.log(kid.getName());  // "trigkit4"
console.log(kid2.getName()); // "trigkit4" (但 kid2.name = undefined)

三、寄生式繼承 (工廠函數增強)

function createChild(parent, extraProps) {
  var child = Object.create(parent); // 原型繼承
  // 增強
  Object.assign(child, extraProps);
  return child;
}

var base = { type: 'widget' };
var enhanced = createChild(base, { 
  render: function() { console.log('Rendering', this.type); },
  version: 1.0
});
enhanced.render(); // "Rendering widget"

四、混入 - 多對象組合 (多重繼承替代)

function mixin(target, ...sources) {
  sources.forEach(src => Object.assign(target, src));
  return target;
}

var canWalk = { walk() { console.log('Walking'); } };
var canSwim = { swim() { console.log('Swimming'); } };
var canFly  = { fly()  { console.log('Flying'); } };

var duck = mixin({}, canWalk, canSwim, canFly);
duck.walk(); // Walking
duck.swim(); // Swimming
duck.fly();  // Flying

五、ES6 Class 糖衣下的原型機制

class Parent {
  constructor(name) { this.name = name; }
  say() { return this.name; }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 必須先調用,建立 this
    this.age = age;
  }
  sayAge() { return this.age; }
}

// 靜態方法也繼承
Parent.create = function(name) { return new Parent(name); };
Child.create('Tom'); // 正常工作 (Child.__proto__ === Parent)

模式選擇決策樹

需要復用代碼
    │
    ├─ 簡單對象擴展 ──► Object.create() / Object.assign() / {...obj, ...extra}
    │
    ├─ 構造函數/類體系
    │     ├─ 單繼承 ──► ES6 class extends (首選)
    │     │            └─ ES5 寄生組合式繼承 (Object.create + call)
    │     │
    │     └─ 多源復用 ──► Mixin / Object.assign / Traits
    │
    └─ 動態行為注入 ──► 寄生式工廠 / 裝飾器模式

避坑總結

  • ❌ Child.prototype = Parent.prototype → 父子共享原型,改一邊壞一邊
  • ❌ 原型上放數組/對象默認值 → 所有實例共享引用
  • ❌ 忘記 Parent.call(this) → 實例屬性不繼承
  • ❌ 忘記修正 constructor → instanceof、類型判斷失效
  • ✅ 現代項目優先 class extends + super()
  • ✅ 複雜組合用 Object.assign/Mixin/裝飾器
copyright © 萬盛學電腦網 all rights reserved