建構函式大家都用得很熟,但如果你是新手,還是有必要搞清楚它到底解決了什麼問題。建構函式用於建立特定型別的物件——它不僅聲明了所使用的物件,還能接受參數,以便第一次建立物件時就設定成員值。你可以自訂自己的建構函式,在其中宣告自訂型別物件的屬性或方法。
在 JavaScript 裡,建構函式通常用來實現實例。JavaScript 沒有 class 的概念,但有特殊的建構函式。透過 new 關鍵字呼叫定義的函式,就等於告訴 JavaScript 你要建立一個新物件,而新物件的成員宣告都來自建構函式內部。在建構函式裡,this 關鍵字引用的正是那個新建立的物件。
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.output = function () {
return this.model + "走了" + this.miles + "公裡";
};
}
var tom = new Car("大叔", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);
console.log(tom.output());
console.log(dudu.output());
這是個非常典型的建構函式,但有兩個小問題。第一,使用繼承很麻煩;第二,output() 在每次建立物件時都被重新定義一次,這代表若有大批實例,同一份函式內容會在記憶體裡重複存在好幾份。
解法之一是把它提到外面,讓所有實例共用同一個函式參照:
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.output = formatCar;
}
function formatCar() {
return this.model + "走了" + this.miles + "公裡";
}
這樣確實只會有一份函式,但全域多了一個 formatCar,有污染命名空間的疑慮。還有更好的方式。
JavaScript 的函式有個原型屬性叫 prototype。當用建構函式建立物件時,掛在該建構函式原型上的屬性,在所有新建立的物件上都可用。於是多個 Car 實例可以共享同一份原型:
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
/*
注意:這裡我們使用了 Object.prototype.方法名,而不是 Object.prototype
主要是用來避免重寫定義原型 prototype 物件
*/
Car.prototype.output = function () {
return this.model + "走了" + this.miles + "公裡";
};
var tom = new Car("大叔", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);
console.log(tom.output());
console.log(dudu.output());
output() 在這裡是所有 Car 實例共享的。那個註解裡的提醒很關鍵:要用 `Car.prototype.output = ...` 逐一掛上,而不要寫成 `Car.prototype = { output: ... }`。後者會整體替換原型物件,把 constructor 屬性一起覆蓋掉,也可能讓先前已建立的實例失去原型連結。
另外一個慣例:建構函式建議以大写字母開頭,以便和普通函式在視覺上區分。ES6 之後的 class 語法會在語法層面強制這個區分,但在 ES5 環境下這仍是重要的自律。
上面的例子都用 new 建立物件,但並非唯一途徑。我們列舉兩種:
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
// 自定義一個 output 輸出內容
this.output = function () {
return this.model + "走了" + this.miles + "公裡";
}
}
// 方法 1:作為函式調用
Car("大叔", 2009, 20000); // 添加到 window 物件上
console.log(window.output());
// 方法 2:在另外一個物件的作用域內調用
var o = new Object();
Car.call(o, "Dudu", 2010, 5000);
console.log(o.output());
方法 1 有點特殊:不使用 new 直接呼叫函式時,非嚴格模式下 this 指向全域物件 window。來驗證一下:
// 作為函式調用
var tom = Car("大叔", 2009, 20000);
console.log(typeof tom); // "undefined"
console.log(window.output()); // "大叔走了20000公裡"
此時 tom 是 undefined,而 window 上卻被莫名其妙地掛了一堆屬性。若改用 new 就沒有這個問題:
// 使用 new 關鍵字
var tom = new Car("大叔", 2009, 20000);
console.log(typeof tom); // "object"
console.log(tom.output()); // "大叔走了20000公裡"
這正是忘記寫 new 時最典型的 bug:全域被污染,而回傳值是 undefined。在嚴格模式('use strict')下 this 會是 undefined,於是 `this.model = model` 直接拋出 TypeError——雖然報錯,但至少不會靜默地污染全域,反而更容易發現問題。
有沒有辦法讓建構函式強制被 new 呼叫?答案是肯定的:
function Car(model, year, miles) {
if (!(this instanceof Car)) {
return new Car(model, year, miles);
}
this.model = model;
this.year = year;
this.miles = miles;
this.output = function () {
return this.model + "走了" + this.miles + "公裡";
}
}
var tom = new Car("大叔", 2009, 20000);
var dudu = Car("Dudu", 2010, 5000);
console.log(typeof tom); // "object"
console.log(tom.output()); // "大叔走了20000公裡"
console.log(typeof dudu); // "object"
console.log(dudu.output()); // "Dudu走了5000公裡"
原理很簡單:用 new 呼叫時,this 是新建立物件、其原型鏈上有 Car.prototype,因此 `this instanceof Car` 為真,繼續執行賦值;沒有用 new 時 this 是全域物件,判斷為假,於是自行補上一個 new 並回傳。兩種呼叫方式都能得到正確結果,這個防禦性寫法在函式庫設計中相當常見。
JavaScript 裡有三種原始包裝函式:Number、String、Boolean。兩種寫法都合法:
// 使用原始包裝函式
var s = new String("my string");
var n = new Number(101);
var b = new Boolean(true);
// 推薦這種
var s = "my string";
var n = 101;
var b = true;
只有在需要保留物件狀態時才該使用包裝函式,差別看下面的程式碼就明白:
// 原始 string
var greet = "Hello there";
// 使用 split() 方法分割
greet.split(' ')[0]; // "Hello"
// 給原始型別添加新屬性不會報錯
greet.smile = true;
// 但沒法獲取這個值
console.log(typeof greet.smile); // "undefined"
// 原始 string(包裝函式版本)
var greet = new String("Hello there");
greet.split(' ')[0]; // "Hello"
// 給包裝函式型別添加新屬性不會報錯
greet.smile = true;
// 可以正常訪問新屬性
console.log(typeof greet.smile); // "boolean"
差別的原因在於:對原始型別的屬性賦值時,引擎會臨時包裝一個物件、設定屬性、然後立刻丟掉這個臨時物件,所以屬性存不住。而 new String 建立的是持久存在的物件,屬性自然留得下來。實務上幾乎總該用字面值寫法,除非你真的需要那個物件身分。
本章講解了建構函式模式的三個層次:基本用法與其記憶體問題、透過 prototype 共享方法的正解、以及 new 關鍵字的行為差異與強制手段。使用時請特別注意兩點:方法要掛在 prototype 上而非建構函式內部;呼叫建構函式時不要漏掉 new,並考慮用 instanceof 做防禦。
參考:https://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript