DIV CSS 佈局教程網

constructor 為什麼會「跑掉」?談 prototype 覆寫的副作用
編輯:JavaScript基礎知識     

constructor 是個熟悉的名字,規則也很簡單:它始終指向建立目前物件的建構函式。麻煩之處在於,當你整體覆寫 prototype 時,這條規則會引發意料之外的結果。

逐項掛上 prototype 時一切正常

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.getAge = function () { return this.age; };
Person.prototype.getName = function () { return this.name; };

var p = new Person("Nicholas", 18);
console.log(p.constructor); // Person(name, age)
console.log(p.getAge());    // 18
console.log(p.getName());   // Nicholas

以「補充成員」的方式擴充時,prototype 物件本身沒有被替換,其上的 constructor 自然還是指向 Person。

整體替換 prototype 之後

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype = {
  getName: function () { return this.name; },
  getAge: function () { return this.age; }
};

var p = new Person("Nicholas", 18);
console.log(p.constructor); // Object()
console.log(p.getAge());    // 18
console.log(p.getName());   // Nicholas

方法都還在,constructor 卻變成了 Object。原因不難理解:prototype 本身就是一個物件,而上面這段等價於:

Person.prototype = new Object({
  getName: function () { return this.name; },
  getAge: function () { return this.age; }
});

既然 constructor 始終指向「建立目前物件的建構函式」,那麼由 Object 產生的這個 prototype,其 constructor 當然就是 Object。

修回來的方法

如果覆寫 prototype 之後仍希望 constructor 指回 Person,在字面值裡補上一行即可:

Person.prototype = {
  constructor: Person,
  getName: function () { return this.name; },
  getAge: function () { return this.age; }
};

實務建議:若只是要新增幾個方法,直接往 prototype 上掛就好;若基於效能或組織考量必須整體替換,記得把 constructor 一起補回去,否則任何依賴 constructor 做型別判斷或原型鏈重建的程式碼都可能出錯。另外要注意屬性描述符的 enumerable 與 writable 設定,直接賦值產生的 constructor 是可枚舉的,與原生行為略有差異。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved