很多人第一次看到 T.constructor = this 這種寫法都會困惑:constructor 本來就該是 Function,為什麼要把它改成某個函式的實例?要回答這個問題,得從原型鏈的回溯機制談起。
Function.prototype.createInstance = function () {
var T = function () {};
T.prototype = this.prototype;
T.constructor = this;
var o = new T();
this.apply(o, arguments);
return o;
}
這裡的 T.constructor = this 看起來沒有實際作用——它設在函式物件自己身上,而查詢原型時走的是 T.prototype.constructor。
Function.prototype.$extends = function (p) {
this.$super = p;
var fn = function () {};
fn.prototype = p.prototype;
this.prototype = new fn();
this.prototype.constructor = this; // 自己加的修正
return this;
};
function Animal() {}
function Cat() {}
Cat.$extends(Animal);
var bb = new Cat();
alert(bb.constructor); // Cat
alert(bb.constructor.prototype.constructor); // 依然是 Cat,不是 Animal
加了 this.prototype.constructor = this 之後,bb.constructor 確實正確指向 Cat,但原型鏈的回溯卻卡住了:bb.constructor.prototype.constructor 又繞回 Cat,永遠到不了 Animal。
Function.prototype.$extends = function (p) {
this.$super = p;
var fn = function () {};
fn.prototype = p.prototype;
this.prototype = new fn();
return this; // 不設定原型的 constructor
};
function Animal() {}
function Cat() {
this.constructor = arguments.callee; // 設在實例上
}
Cat.$extends(Animal);
var bb = new Cat();
alert(bb.constructor); // Cat
alert(bb.constructor.prototype.constructor); // Animal,回溯成功
差別在於:constructor 設在原型的 constructor 上,回溯會停在子類;設在實例自身,才能沿著原型鏈一層層往上走到父類。
var f = function () {}
alert(f instanceof Function); // true
var obj = new f;
alert(obj instanceof Function); // false
f.prototype = Function.prototype; // 不推薦:會污染 Function.prototype
f.prototype = new Function(); // 正確做法
f.prototype.name = "zhouyang"; // 不會影響 Function 的原型
f.prototype.constructor = f;
obj = new f;
alert(obj instanceof Function); // true
alert(obj.constructor.prototype.constructor); // 仍是 f,只能回溯一層
為什麼要費心維護 constructor?因為 __proto__ 對使用者不可見,當手上只有一個物件、不知道它是怎麼被實例化出來的時候,唯一的入口就是 obj.constructor,再透過它取得 prototype。若把 constructor 設在實例上,就能多回溯一層到父類原型。
結論:constructor 的作用就是維護物件原型鏈的可回溯性。至於「原型污染」,指的是直接修改 Function.prototype 這類內建原型所帶來的連帶影響——例如替 f.prototype 加一個 name,結果 Function 的原型也多了一個 name。
var f = function (x) {}
f.prototype = {};
alert((new f).constructor); // Object
f.prototype.constructor = f;
alert((new f).constructor); // f
最後這段說明:一旦整體替換 prototype,constructor 就會指向新的原型物件自身的 constructor(此例為 Object),必須手動補回來。