類與繼承機制的出現,代表 JavaScript 已具備大規模開發的門檻。ECMAScript 4 曾試圖引入類與模組,但一次加入太多特性反而讓語言失控,最終被否決,類因此延後到 ES6。截至目前,JavaScript 仍沒有真正意義上的 class(ES6 的 class 本質上也是語法糖),但我們完全可以模擬它。本文從原型機制談到各種類工廠的實作。
在其他語言中,實例都要透過建構子 new 出來。作為一個刻意模仿 Java 的語言,JavaScript 有 new 運算子,且所有函式都能當建構子使用。瀏覽器為了建構它龐大的生態(Node、Element、HTMLElement、HTMLParagraphElement……),顯然需要某種共享機制,於是借鑑了「原型」。
Prototype 作為一個特殊屬性存在於每個函式上。當函式被 new 出「孩子」(實例)時,該實例就擁有了函式 prototype 上的一切成員,从而实现所有實例共享同一組方法或屬性。而 JavaScript 所謂的「類」,就是透過修改這個 prototype 物件來區隔原生物件與自訂類型。
function A() {}
A.prototype = {
aa: "aa",
method: function () {}
};
var a = new A;
var b = new A;
console.log(a.aa === b.aa); // true
console.log(a.method === b.method); // true
定義在原型上的方法叫「原型方法」,為所有實例共享。为实现差異化,JavaScript 允許在建構子內直接指定方法,這叫「特權方法」;若是屬性則叫「特權屬性」,每個實例一份、互不干擾。因此常見做法是:共享的操作型方法放原型,私有屬性放特權屬性;若連 this 上都不希望被存取,就放進函式體的閉包裡,成為名副其實的私有屬性。
function A() {
var count = 0; // 真正的私有屬性
this.aa = "aa";
this.method = function () {
return count;
};
this.obj = {};
}
A.prototype = {
aa: "aa",
method: function () {}
};
var a = new A;
var b = new A;
console.log(a.aa === b.aa); // true:基本型別比較值
console.log(a.obj === b.obj); // false:每次呼叫都重新建立
console.log(a.method === b.method); // false
特權方法只是遮住了原型的同名成員,因此刪掉特權方法就能重新取得原型版本:
delete a.method; delete b.method; console.log(a.method === A.prototype.method); // true console.log(a.method === b.method); // true
用 Java 的術語說,原型方法與特權方法都屬於實例方法;Java 另有類方法與類屬性,在 JavaScript 中直接掛在函式上即可:
A.method2 = function () {} // 類方法
var c = new A;
console.log(c.method2); // undefined
既然原型上有什麼、實例就有什麼,那麼把子類的 prototype 換成父類的 prototype,就輕易繼承了父類的所有原型成員:
function A() {}
A.prototype = { aaa: 1 };
function B() {}
B.prototype = A.prototype;
var b = new B;
console.log(b.aaa); // => 1
A.prototype.bb = 2;
console.log(b.bb); // => 2
但因為兩者指向同一個物件,改 A 的原型等同改 B 的原型,一個物件不能同時賦給兩個類。解法有兩種。
用 for-in 把父類原型成員逐一拷給子類原型。好處是簡單直接,壞處是無法用 instanceof 驗證。Prototype.js 的 extend 就是做這件事:
function extend(des, source) {
// des = destination
for (var property in source) {
des[property] = source[property];
}
return des;
}
透過一個「橋接函式」製造原型鏈:
function A() {}
A.prototype = { aa: function () { alert(1); } };
function bridge() {}
bridge.prototype = A.prototype;
function B() {}
B.prototype = new bridge();
var a = new A;
var b = new B;
console.log(a == b); // false,原型已分離
console.log(A.prototype == B.prototype); // false
console.log(a.aa === b.aa); // true,共享父類方法
// 為父類動態添加新方法
A.prototype.bb = function () { alert(2); }
console.log(b.bb === A.prototype.bb); // true
// 子類自己的方法
B.prototype.cc = function () { alert(3); }
console.log(a.cc === b.cc); // false,父類沒有子類的東西
// 能正常通過 instanceof 驗證
console.log(b instanceof A); // true
console.log(b instanceof B); // true
ES5 內建了這種做法,即 Object.create。不考慮第二個參數時,它約等於:
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
}
不過原型繼承並不會自動帶入父類的類成員與特權成員,這些得自己補:類成員用 extend 拷貝,特權成員則在子類建構子中透過 apply 執行父類建構子。
function inherit(init, Parent, proto) {
function Son() {
Parent.apply(this, arguments); // 先繼承父類特權成員
init.apply(this, arguments); // 再執行自己的建構子
}
Son.prototype = Object.create(Parent.prototype, {});
Son.prototype.toString = Parent.prototype.toString; // 處理 IE bug
Son.prototype.valueOf = Parent.prototype.valueOf; // 處理 IE bug
Son.prototype.constructor = Son; // 確保建構子指向正確
extend(Son, proto); // 加入子類特有的原型成員
return Son;
}
存取物件屬性時,引擎會先找特權成員,再找原型,然後沿原型鏈往上。那麼改動原型或 constructor 能否影響結果?
function A() {}
A.prototype = { aa: 1 };
var a = new A;
console.log(a.aa); // => 1
// 整個原型換掉
A.prototype = { aa: 2 };
console.log(a.aa); // => 1,不受影響
// 試著改 constructor
function B() {}
B.prototype = { aa: 3 };
a.constructor = B;
console.log(a.aa); // => 1,仍然不受影響
可見回溯並非走 constructor 這條路。查 ECMAScript 規範可知,每個物件還有一個內部屬性 [[Prototype]],保存 new 它時建構子所引用的 prototype。標準瀏覽器與 IE11 以上把它暴露為 __proto__:
function A() {
console.log(this.__proto__.aa); // 1
this.aa = 2;
}
A.prototype = { aa: 1 };
var a = new A;
console.log(a.aa); // => 2(特權屬性優先)
a.__proto__ = { aa: 3 };
console.log(a.aa); // => 2
delete a.aa; // 移除特權屬性,露出原型鏈上的同名屬性
console.log(a.aa); // => 3
new 運算子實際做了五件事:
instance.__proto__ = Klass.prototypethis = instance有了 __proto__,繼承可以寫得更簡潔:
function A() {}
A.prototype = { aa: 1 };
function bridge() {}
bridge.prototype = A.prototype;
function B() {}
B.prototype = new bridge();
B.prototype.constructor = B;
var b = new B;
B.prototype.cc = function () { alert(3); }
console.log(B.prototype.__proto__ === A.prototype); // true
console.log(b.__proto__ == B.prototype); // true
console.log(b.__proto__.__proto__ === A.prototype); // true,取得父類原型
既然 B.prototype.__proto__ 就是 A.prototype,那麼直接寫 B.prototype.__proto__ = A.prototype 也能完成兩個類的繼承。__proto__ 已進入 ES6 規範,可以較放心地使用(ES6 的 class 繼承正是建立在這套機制上)。
前面的繼承實作都略顯凌亂。我們真正想要的是一個專用方法:傳入參數或遵循簡單格式,就能建立一個類,特別是子類。
主流框架的類工廠往往依賴大量工具函式,而一個精巧的類工廠其實百行內就能完成。P.js 是相當精緻的例子——呼叫父類同名方法時,它直接把父類原型拋在面前,連 _super 都省了。
var P = (function (prototype, ownProperty, undefined) {
return function P(_superclass /* = Object */, definition) {
// 若沒給父類,則第一個參數就是 definition
if (definition === undefined) {
definition = _superclass;
_superclass = Object;
}
// C 是最終要回傳的類。
// 呼叫時會建立並初始化 C 的實例;
// 若 this 已是 C 的實例,則只初始化 this
function C() {
var self = this instanceof C ? this : new Bare;
self.init.apply(self, arguments);
return self;
}
// C.Bare 是一個建構子為 no-op 的類,
// 其原型與 C 相同,因此 C.Bare 的實例也是 C 的實例。
// 用它可以在不呼叫 init 的情況下建立 C 的實例
function Bare() {}
C.Bare = Bare;
// 建立原型鏈
var _super = Bare[prototype] = _superclass[prototype];
var proto = Bare[prototype] = C[prototype] = C.p = new Bare;
var key;
proto.constructor = C;
C.extend = function (def) {
return P(C, def);
};
return (C.open = function (def) {
if (typeof def === 'function') {
// 以 (proto, _super, C, _superclass) 呼叫定義函式
def = def.call(C, proto, _super, C, _superclass);
}
if (typeof def === 'object') {
for (key in def) {
if (ownProperty.call(def, key)) {
proto[key] = def[key];
}
}
}
// 若沒有 init,表示繼承的是非 Pjs 類,直接沿用父類建構子
if (!('init' in proto)) {
proto.init = _superclass;
}
return C;
})(definition);
};
// 為了壓縮時的最佳化,把幾個輔助值與 'prototype' 字串閉包進來
// (C[p] 比 C.prototype 短得多)
})('prototype', ({}).hasOwnProperty);
建立一個簡單的類:
var Dog = P(function (proto, superProto) {
proto.init = function (name) {
this.name = name;
};
proto.move = function (meters) {
console.log(this.name + " moved " + meters + " m.");
}
});
var a = new Dog("aaa");
var b = new Dog("bbb");
a.move(1);
b.move(2);
建立子類並呼叫父類方法:
var Animal = P(function (proto, superProto) {
proto.init = function (name) {
this.name = name;
};
proto.move = function (meters) {
console.log(this.name + " moved " + meters + " m.");
};
});
var Snake = P(Animal, function (snake, animal) {
snake.init = function (name, eyes) {
animal.init.call(this, arguments); // 呼叫父類建構子
this.eyes = 2;
};
snake.move = function () {
console.log('slithering...');
animal.move.call(this, 5); // 呼叫父類同名方法
};
});
var s = new Snake("snake", 1);
s.move();
console.log(s.name);
console.log(s.eyes);
私有屬性的處理也很乾淨——因為定義都集中在函式體內,天然就是安全的:
var Cobra = P(Snake, function (cobra) {
var age = 1; // 私有屬性,此處亦可定義私有方法
cobra.glow = function () {
return age++; // 「長大」
};
});
var c = new Cobra("cobra");
console.log(c.glow()); // 1
console.log(c.glow()); // 2
console.log(c.glow()); // 3
對比ES6 的 class / extends / super,會發現 P.js 在 2013 年前後提出的這些手法,幾乎都被語言本身吸收並內建了。理解這段演化過程的價值,在於明白語法糖底下究竟發生了什麼——以及為什麼 class 宣告不會被提升(hoisting)、為什麼子類建構子中存取 this 會出錯。