JavaScript 沒有真正的類繼承,只能通過在原對象上添加或改寫屬性來模擬。本文用實例對比 prototype、apply、call 三種模擬繼承的方式,並分析它們的取捨。
先定義一個父類:
? 1 2 3 4 5 6 7 8 9 //父類 function ParentClass() { this.className = "ParentClass"; this.auth = "Auth"; this.version = "V1.0"; this.parentClassInfo = function () { return this.className + "\n" + this.auth + "\n" + this.version; } }
? 1 2 3 4 5 6 7 8 9 10 11 12 function ChildClassByPrototype() { this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } } ChildClassByPrototype.prototype = new ParentClass(); var cctest1 = new ChildClassByPrototype();
這種方式很簡單:把父類的實例賦給子類的 prototype 即可。它利用的是原型鏈向上查找的特性——調用 cctest1.parentClassInfo() 時,JS 先在實例中找,找不到就沿原型鏈找到 ParentClass 實例上的方法。
? 1 2 3 4 5 6 7 8 9 function ChildClassByApply() { ParentClass.apply(this, new Array()); this.date = "2013-07-26"; this.classInfo = function () { return this.parentClassInfo() + "\n" + this.date; } }
apply 可理解為用 A 方法替換 B 方法:第一個參數是 B 的 this,第二個參數是要傳給 A 的參數數組。
? 1 2 3 4 5 6 7 8 9 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 只實現了方法替換,沒有複製對象屬性。
每種方法都有適用環境。若父類帶有參數的構造函數:
? 1 2 3 4 5 6 7 8 function ParentClass(className, auth, version) { this.className = className; this.auth = auth; this.version = version; ... }
這種情況下 prototype 就不適用了,可選用 apply 或 call:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function ChildClassByApply(className, auth, version) { ParentClass.apply(this, [className, auth, version]); ... } function ChildClassByCall(className, auth, version) { ParentClass.call(this, arguments[0], arguments[1], arguments[2]); ... } ChildClassByCall.prototype = new ParentClass();
那 apply 和 call 又該如何取捨?在 OO 繼承中,子類應該也是父類的類型,即用 instanceof 檢測時,ChildClassByCall 應同時是 ParentClass 類型。但實測會發現,僅用 apply 繼承的子類並非 ParentClass 類型。因此建議使用 call + prototype 來模擬繼承。據說 Google Map API 的繼承正是採用這種方式。