標籤:執行個體化 代碼 prototype zha bsp return color name tor
constructor始終指向建立當前對象的建構函式。比如下面例子:
// 等價於 var foo = new Array(1, 56, 34, 12);var arr = [1, 56, 34, 12];console.log(arr.constructor === Array); // true// 等價於 var foo = new Function(); var Foo = function() { };console.log(Foo.constructor === Function); // true// 由建構函式執行個體化一個obj對象var obj = new Foo();console.log(obj.constructor === Foo); // true // 將上面兩段代碼合起來,就得到下面的結論console.log(obj.constructor.constructor === Function); // true
但是當constructor遇到prototype時,有趣的事情就發生了。
我們知道每個函數都有一個預設的屬性prototype,而這個prototype的constructor預設指向這個函數。如下例所示:
function Person(name) { this.name = name;};Person.prototype.getName = function() { return this.name;};var p = new Person("ZhangSan");console.log(p.constructor === Person); // trueconsole.log(Person.prototype.constructor === Person); // true// 將上兩行代碼合并就得到如下結果console.log(p.constructor.prototype.constructor === Person); // true
當時當我們重新定義函數的prototype時(注意:和上例的區別,這裡不是修改而是覆蓋),
constructor的行為就有點奇怪了,如下樣本:
function Person(name) { this.name = name;};Person.prototype = { getName: function() { return this.name; }};var p = new Person("ZhangSan");console.log(p.constructor === Person); // falseconsole.log(Person.prototype.constructor === Person); // falseconsole.log(p.constructor.prototype.constructor === Person); // false
為什麼呢?
原來是因為覆蓋Person.prototype時,等價於進行如下代碼操作:
Person.prototype = new Object({ getName: function() { return this.name; }});
而constructor始終指向建立自身的建構函式,所以此時Person.prototype.constructor === Object,即是:
function Person(name) { this.name = name;};Person.prototype = { getName: function() { return this.name; }};var p = new Person("ZhangSan");console.log(p.constructor === Object); // trueconsole.log(Person.prototype.constructor === Object); // trueconsole.log(p.constructor.prototype.constructor === Object); // true
怎麼修正這種問題呢?方法也很簡單,重新覆蓋Person.prototype.constructor即可:
function Person(name) { this.name = name;};Person.prototype = {
constructor: Person, getName: function() { return this.name; }};var p = new Person("ZhangSan");console.log(p.constructor === Person); // trueconsole.log(Person.prototype.constructor === Person); // trueconsole.log(p.constructor.prototype.constructor === Person); // true
js中的constructor與prototype