constructor 這個屬性看起來單純,卻是許多人對原型鏈感到困惑的起點。理解它,等於理解 JavaScript 物件 internally 是如何自我指涉的。
constructor 屬性回傳一個參照,指向建立目前物件的函式。語法很簡單:
object.constructor
一句話總結:constructor 永遠指向「建立目前物件的建構函式」。
先看最典型的寫法:
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 屬性,而這個 prototype 物件上的 constructor 會指回該函式本身,形成一個閉環。
但若是改成這樣寫:
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。
關鍵在於,上面的整體指派實際上等價於:
Person.prototype = new Object({
getName: function () { return this.name; },
getAge: function () { return this.age; }
});
既然是用 Object 建立的新物件,它的 constructor 自然指向 Object。原本那個「指回 Person」的連結,在整體覆寫的瞬間就被丟掉了。
這也解釋了為什麼「逐一附加屬性」(Person.prototype.xxx = ...)不會出問題,而「整體替換物件字面量」就會——前者是在原物件上增修,後者則是換了一個全新的物件。
解法很單純,在字面量中明確把 constructor 補回去:
Person.prototype = {
constructor: Person,
getName: function () { return this.name; },
getAge: function () { return this.age; }
};
直接賦值雖然有效,但會讓 constructor 變成可列舉([[Enumerable]] 為 true),而原生的 constructor 預設是不可列舉的。若在意這個差異——例如有用 for...in 走訪——可以改用 Object.defineProperty:
Object.defineProperty(Person.prototype, "constructor", {
enumerable: false,
value: Person
});
坦白說,大多數應用程式中 constructor 的值是否正確並不影響功能,因為日常幾乎不會直接讀它。它真正重要的場合有兩個:
一是框架與工具庫的型別判斷。有些程式庫會用 obj.constructor === SomeClass 或 obj.constructor.name 來識別物件型別,constructor 錯了就會誤判。
二是除錯的可讀性。在 DevTools 中檢視物件時,展開的標題就是 constructor 的名稱。若顯示 Object 而非 Person,追資料來源時會平白多花力氣。
最後補充一點:ES6 的 class 語法只是原型繼承的語法糖,但它會自動處理好 constructor 的指向,因此改用 class 撰寫時並不會遇到這個問題。這也是建議新專案優先採用 class 的理由之一。