構造函數本質上就是「搭配 new 呼叫的一般函數」。當用 new 執行時,函式內部的 this 會指向剛建立出來的新物件。
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
var person = new Person("Nicholas", 29, "Software Engineer");
這段程式碼為新物件設定了 name、age、job 三個屬性。
問題出在 this 是執行期綁定的。若直接呼叫 Person() 而不加 new,在非嚴格模式下 this 會落到全域物件 window 上,於是屬性被寫到 window 裡:
var person = Person("Nicholas", 29, "Software Engineer");
alert(window.name); // "Nicholas"
alert(window.age); // 29
alert(window.job); // "Software Engineer"
更麻煩的是,window.name 本身是有用途的屬性(用來標識 frame 或連線目標),被意外覆寫後可能在頁面上引發一連串難以追查的錯誤。
思路是在動手賦值之前,先確認 this 是不是正確型別的實例;如果不是,就自己補上 new。
function Person(name, age, job) {
if (this instanceof Person) {
this.name = name;
this.age = age;
this.job = job;
} else {
return new Person(name, age, job);
}
}
var person1 = Person("Nicholas", 29, "Software Engineer");
alert(window.name); // ""
alert(person1.name); // "Nicholas"
var person2 = new Person("Shelby", 34, "Ergonomist");
alert(person2.name); // "Shelby"
加與不加 new,都會拿到一個正確的 Person 實例,全域物件不再被污染。
一旦採用這個模式,就等於鎖死了「可以用什麼環境呼叫構造函數」。如果你用「構造函數竊取」來做繼承、又沒搭配原型鏈,繼承鏈很可能就斷了:
function Polygon(sides) {
if (this instanceof Polygon) {
this.sides = sides;
this.getArea = function () { return 0; };
} else {
return new Polygon(sides);
}
}
function Rectangle(width, height) {
Polygon.call(this, 2);
this.width = width;
this.height = height;
this.getArea = function () { return this.width * this.height; };
}
var rect = new Rectangle(5, 10);
alert(rect.sides); // undefined
Polygon 是作用域安全的,但 Rectangle 不是。當 Polygon.call(this, 2) 執行時,Rectangle 的 this 並非 Polygon 的實例,於是 Polygon 選擇「建立並回傳一個新物件」。Rectangle 內部的 this 完全沒有被擴充,而 Polygon.call() 的回傳值又沒被使用,結果 sides 就消失了。
Rectangle.prototype = new Polygon(); var rect = new Rectangle(5, 10); alert(rect.sides); // 2
這麼寫之後,每個 Rectangle 實例同時也是 Polygon 實例,Polygon.call() 便會照預期執行,sides 也就正常掛上來了。若再加上寄生組合繼承,還能避免呼叫父構造函數兩次的多餘開銷。