構造函數用於創建特定類型的物件——它不僅聲明了使用的物件,還能接受參數以便第一次創建時設置成員值。你可以自定義構造函數,在其中宣告自訂類型物件的屬性或方法。
JavaScript沒有類的概念,但有特殊的構造函數。透過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()在每次創建物件時都重新定義了。最好的做法是讓所有Car實例共享同一個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 + "公裡";
}
這方式可用,但我們還有更好的做法。
JavaScript裡函數有個原型屬性叫prototype,當調用構造函數創建物件時,所有該構造函數原型的屬性在新物件上都可用。因此多個Car實例可以共享同一個原型:
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
/*
注意:這裡使用 Car.prototype.方法名,而非 Car.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實例間共享。另外,我們推薦構造函數以大寫字母開頭,以便和普通函數區分。
上面的例子都用new來創建物件,但其實還有別的方式:
// 方法1:作為函數調用(添加到 window 物件上)
Car("大叔", 2009, 20000);
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.output()卻能正確輸出。若使用new則沒有這個問題:
var tom = new Car("大叔", 2009, 20000);
console.log(typeof tom); // "object"
console.log(tom.output()); // "大叔走了20000公裡"
既然不用new會出問題,能否讓構造函數強制使用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(typeof dudu); // "object"
透過判斷this是否為Car的實例來決定返回new Car還是繼續執行:用了new時(this instanceof Car)為真,繼續賦值;沒用new時為假,就重新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";
greet.split(' ')[0]; // "Hello"
greet.smile = true; // 給原始類型加屬性不會報錯
console.log(typeof greet.smile); // "undefined"(拿不到)
// 包裝函數
var greet = new String("Hello there");
greet.smile = true;
console.log(typeof greet.smile); // "boolean"(可正常訪問)
本章講解了構造函數模式的使用方法、調用方式,以及new關鍵字的相關注意事項,希望你在使用時能多加留意。