JavaScript 原型繼承雖強大,但傳統類式寫法需大量樣板代碼。John Resig(jQuery 作者)在《Simple JavaScript Inheritance》中提出約 25 行的 `Class.extend` 實現,支援單一繼承、`_super` 呼叫父類方法、建構子初始化分離,成為眾多庫(Backbone 早期、Base2)的藍本。
var Person = Class.extend({
init: function(isDancing) {
this.dancing = isDancing;
},
dance: function() {
return this.dancing;
}
});
var Ninja = Person.extend({
init: function() {
this._super(false); // 呼叫父類 init
},
dance: function() {
return this._super(); // 呼叫父類 dance
},
swingSword: function() {
return true;
}
});
var p = new Person(true);
p.dance(); // true
var n = new Ninja();
n.dance(); // false
n.swingSword(); // true
// instanceof 鏈完整
console.log(p instanceof Person && p instanceof Class); // true
console.log(n instanceof Ninja && n instanceof Person && n instanceof Class); // true
(function() {
var initializing = false, // 標記是否處於「建構原型」階段
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // 檢測函數 toString 是否包含 _super
// 基礎 Class(不做任何事)
this.Class = function() {};
// 靜態 extend 方法:創建子類
Class.extend = function(prop) {
var _super = this.prototype; // 父類原型
// 1. 實例化父類作為子類原型(但不執行 init)
initializing = true;
var prototype = new this();
initializing = false;
// 2. 複製/包裝屬性到新原型
for (var name in prop) {
// 檢測:覆寫父類函數 且 函數體引用 _super
prototype[name] = typeof prop[name] === 'function' &&
typeof _super[name] === 'function' &&
fnTest.test(prop[name])
? (function(name, fn) {
return function() {
var tmp = this._super; // 保存舊 _super
this._super = _super[name]; // 注入父類同名方法
var ret = fn.apply(this, arguments); // 執行當前方法
this._super = tmp; // 還原
return ret;
};
})(name, prop[name])
: prop[name]; // 非函數或無 _super 引用:直接複製
}
// 3. 子類建構子
function Class() {
if (!initializing && this.init) this.init.apply(this, arguments);
}
// 4. 連接原型鏈
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = arguments.callee; // 繼承 extend 靜態方法
return Class;
};
})();
| 方案 | 特點 | 適用場景 |
|---|---|---|
| ES6 `class` / `extends` | 原生語法、靜態分析友好、支援 `super()`、私有欄位 `#` | 所有現代專案(需透譯支援舊瀏覽器) |
| TypeScript `class` + `implements` | 介面約束、存取修飾符、裝飾器 | 大型團隊、嚴格型別專案 |
| Object.create + 工廠函數 | 組合優於繼承、無 `this` 綁定困擾、函數式風格 | 偏好組合、避免類層級 |
| Resig Class.extend | 無構建工具、極輕量、IE6+ 相容 | 舊專案維護、嵌入式腳本、教學示範 |
class Person {
constructor(isDancing) { this.dancing = isDancing; }
dance() { return this.dancing; }
}
class Ninja extends Person {
constructor() { super(false); }
dance() { return super.dance(); }
swingSword() { return true; }
}
Resig 的 `Class.extend` 是 JavaScript 歷史上極具影響力的輕量繼承實現,展示了「原型鏈模擬類」、「建構子分離」、「運行時 `_super` 注入」三大核心技巧。現代開發應優先使用 ES6 `class`,享受語法糖、靜態分析、引擎優化優勢。理解其原理有助於閱讀舊代碼庫、在無構建環境下快速構建類結構、深刻理解 JavaScript 物件模型本質。