眾所周知,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 實現:
//子類 //1、prototype繼承 function ChildClassByPrototype() { this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } } ChildClassByPrototype.prototype = new ParentClass(); var cctest1 = new ChildClassByPrototype(); cctest1.parentClassInfo(); cctest1.classInfo();這種寫法最為簡潔,只要把父類的實例指派給子類的 prototype,子類便能使用父類的方法與屬性。背後靠的是原型鏈向上查找的特性:當呼叫 cctest1.parentClassInfo() 時,JavaScript 先在子類實例中尋找,找不到就沿著 prototype 往上找,最終在 ParentClass 的實例中找到並執行。
二、透過 apply 實現:
//2、apply繼承 function ChildClassByApply() { ParentClass.apply(this, new Array()); //ParentClass.apply(this, []); this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } }apply 可以理解為用 A 方法替換 B 方法:第一個參數是 B 方法所屬的物件本身,第二個參數則是要傳給 A 方法的參數陣列;若沒有參數,傳入 new Array() 或空陣列 [] 即可。
三、call + prototype 實現:
//3、call+prototype繼承 function ChildClassByCall() { ParentClass.call(this, arguments); this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } } ChildClassByCall.prototype = new ParentClass();call 與 apply 作用相似,差別在參數傳遞方式:call 的第一個參數同樣是 B 方法的物件本身,後續參數則無需包成陣列,直接依序傳入即可。既然作用相近,為何還要多加上原型指派?這是因為 call 只完成了方法的替換,並未複製物件屬性。
每種方法都有適用的場合。舉例來說,若父類帶有有參構造函式:
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; } }這種情況下 prototype 就不適用,應改用 apply 或 call:
function ChildClassByApply(className, auth, version) { ParentClass.apply(this, [className, auth, version]); this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } } function ChildClassByCall(className, auth, version) { ParentClass.call(this, arguments[0], arguments[1], arguments[2]); //ParentClass.call(this, className, auth, version); this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } } ChildClassByCall.prototype = new ParentClass();實例化方式如下:
var cctest2 = new ChildClassByApply("ParentClass", "Auth", "V1.0"); var cctest3 = new ChildClassByCall("ParentClass", "Auth", "V1.0");那麼 apply 與 call 之間又該如何取捨?在物件導向的繼承觀念裡,子類繼承父類後,理應「也是」父類的型別。但用 instanceof 檢測會發現,單靠 apply 繼承的子類並不被判定為 ParentClass 型別。因此,比較建議的做法是采用 call + prototype 來模擬繼承。據說 Google Map API 的繼承正是採用這種方式。
希望本文對你的 JavaScript 設計有所幫助。