在撰寫一本 JavaScript 書籍的過程中,我曾花費不少時間研究這門語言的繼承體系,並比較了各式各樣模擬傳統類別繼承的方案。在眾多實作裡,我最欣賞的莫過於 base2 與 Prototype 的做法。
從這些方案出發,其實可以濃縮出一套兼具思想內涵的框架:它必須簡單、可重用、易於理解,而且不依賴任何外部函式庫。其中,簡單與實用是重中之重。先看看它的使用方式:
var Person = Class. extend ( { init: function (isDancing ) { this. dancing = isDancing; }, dance: function ( ) { return this. dancing; } } ); var Ninja = Person.extend({ init: function(){ this._super( false ); }, dance: function(){ // Call the inherited version of dance() return this._super(); }, swingSword: function(){ return true; } }); var p = new Person(true); p.dance(); // => true var n = new Ninja(); n.dance(); // => false n.swingSword(); // => true // Should all be true p instanceof Person && p instanceof Class && n instanceof Ninja && n instanceof Person && n instanceof Class 這裡有幾個值得留意的重點:
整體成果讓我相當滿意:類別的定義變得結構清晰,維持單一繼承,同時還能呼叫父類方法。
以下是它的實作(為方便閱讀並附上註解),大約二十五行左右,歡迎交流指教。
/* Simple JavaScript Inheritance * By John Resig https://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype ( function ( ) { var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); 其中,「初始化(initializing / 不呼叫 init)」與「建立 _super 方法」是最棘手的部分。接下來我會做個簡要說明,幫助大家理解其運作機制。
為了說明這種基於函式原型的繼承方式,先看傳統做法:將子類的 prototype 屬性指向父類的一個實例,如下:
function Person ( ) { } function Ninja ( ) { } Ninja. prototype = new Person ( ); // Allows for instanceof to work: (new Ninja()) instanceof Person 然而,這裡的難題在於:我們只想要「是否為實例」的效果,卻不希望真的去建立一個 Person 實例並觸發其建構子。為避免這個副作用,程式碼中設定了一個布林參數 initializing,只有在建立父類實例並將它指派給子類的 prototype 時,其值才為 true。如此一來,就能區分「真正的實例化」與「建立繼承時的建構子呼叫」,並在真正的實例化時才呼叫 init:
if ( !initializing ) this.init.apply(this, arguments);
這一點格外重要,因為 init 函式裡可能藏著相當耗費資源的運算(例如連線伺服器、建立 DOM 元素等),誰也無法預先斷定,所以做出區分是完全必要的。
使用繼承時,最常見的需求就是讓子類能存取父類中被覆寫的方法。在這套實作下,做法是提供一個臨時的 ._super 方法,它指向父類方法,且只能在子類方法內部取用。
var Person = Class. extend ( { init: function (isDancing ) { this. dancing = isDancing; } } ); var Ninja = Person.extend({ init: function(){ this._super( false ); } }); var p = new Person(true); p.dancing; // => true var n = new Ninja(); n.dancing; // => false 要實現這個功能需要幾個步驟。首先,我們用 extend 把基本的 Person 實例(類別實例,前面提到過其建構過程)與傳入的字面物件合併。合併時做了幾個檢查:先確認待合併的屬性是否為函式,若是,再檢查被覆寫的父類屬性是否也是函式;若兩項都成立,就為該屬性準備 _super 方法。
這裡建立了一個匿名閉包(回傳函式物件)來包裝新增的 super 方法。基於維護執行環境的考量,我們應先把舊的 this._super(無論是否存在)暫存起來,等函式執行完再還原,這有助於避免同名屬性導致的不可預期問題。
接著建立新的 _super 方法,它指向父類中被覆寫的方法。所幸我們不必對 _super 做任何改動或切換作用域,因為函式的執行環境會隨著呼叫它的物件自動改變(this 會指向父類)。
最後,呼叫字面物件的方法,執行過程中可能會用到 this._super(),執行完畢後把 _super 屬性還原成原本的狀態,再 return 結束函式。
當然,達到相同效果的方法有很多種(我曾見過把 super 綁定到自身、再用 arguments.callee 存取的做法),但始終覺得這個方案最能兼顧實用性與簡潔性。
在我完成的多個基於 JavaScript 原型的工作裡,唯有這套類別繼承實作是我願意公開分享的。我相信,簡潔的程式碼(易於學習、易於繼承、下載量更小)更值得提出來共同探討。因此,對於想理解 JavaScript 類別構造與繼承的人來說,這是個不錯的起點。