要用好 Prototype 這類框架,得先搞得懂它背後那套 JavaScript 物件導向的寫法。JavaScript 沒有 class 關鍵字(在 ES6 之前),所有物件導向都得靠函式與 prototype 手動搭出來。這一篇把基本模式整理清楚。
用建構函式加 this 指派,就得到公有屬性與方法:
function test1(){
this.p1 = "p1";
this.p2 = "p2";
this.f1 = function(){ alert("f1"); };
this.f2 = function(){ alert("f2"); };
}
在建構函式裡用 var 宣告的變數,作用域被關在函式內部,外部無法直接存取:
function test1(){
var _test = "test"; // 私有,對外不公開
this.p1 = "p1";
this.p2 = "p2";
this.f1 = function(){ alert("f1"); };
}
直接掛在函式物件上即可,不需要建立實例就能存取:
test1.staticProp = "static var";
test1.staticMethod = function(){
alert("static method");
};
掛在 prototype 上的屬性與方法,會被所有實例共用,而且只會建立一份,比放在建構函式裡省記憶體:
test1.prototype.prop2 = "prop2";
test1.prototype.method2 = function(){
alert(this.prop2);
};
也可以一次指派一整個物件,寫起來更清爽——這是最常見的 Prototype 類別寫法:
function test(){}
test.prototype = {
p1: "p1",
p2: "p2",
f1: function(){ alert("f1"); }
};
最直覺的做法是用 for...in 遍歷父類的 prototype,把每個成員複製到子類:
function test1(){} // 新的子類
var p;
for (p in test.prototype) { // 遍歷父類所有屬性與方法
test1.prototype[p] = test.prototype[p]; // 全部複製過來
}
test1.prototype.newMethod = function(){ // 子類自己的新方法
alert("new method");
};
上面那段迴圈,Prototype 用 Object.extend 包裝成一個方法:
Object.extend = function(destination, source){
for (var property in source){
destination[property] = source[property];
}
return destination;
};
兩個參數分別對應子類與父類,所以前面的繼承可以簡化成:
function test1(){
test1.prototype = Object.extend({
newMethod: function(){
alert("new method");
}
}, test.prototype);
}
如果把兩個參數對調:
function test1(){
test1.prototype = Object.extend(
test.prototype,
{
newMethod: function(){
alert("new method");
}
}
);
}
對 test1 這個子類來說,效果完全相同——它一樣拿到了父類的所有成員加上新方法。
但差別在於:父類 test 也變成了帶有 newMethod 的那一個,因為 Object.extend 的 destination 被直接修改了。這不是我們要的繼承,但反過來看,這恰好提供了一個「隨時為既有物件擴充方法」的手段——Prototype 整個函式庫大量依賴的,正是這個特性。
補充一點現實面的演變,免得你把力氣花錯地方:
ES5 提供了 Object.create(),用原型鏈做真正的委派式繼承,不必複製屬性:
function Test1(){}
Test1.prototype = Object.create(Test.prototype);
Test1.prototype.newMethod = function(){ alert("new method"); };
ES6 的 class 語法把這一切包成熟悉的樣子(本質仍是原型,只是語法糖):
class Test {
constructor(){ this.p1 = "p1"; }
f1(){ alert("f1"); }
}
class Test1 extends Test {
newMethod(){ alert("new method"); }
}
而 Object.assign(target, source) 就是原生的 Object.extend,不用再自己實作。
理解 for...in 複製與原型鏈的差異,你才能判斷該用哪一種——複製式繼承會在子類被建立的那一刻定格,父類之後的變動不會反映到子類;原型鏈式則是動態查找,父類改了子類立刻看得到。這個差異,在真實專案裡咬過不少人。