JavaScript 建立物件的方式相當多,從最原始的逐個賦值,到兼顧效能與可讀性的組合模式,各有適用場合。以下依序梳理並比較其優缺點。
最基礎的做法:先呼叫 Object 建構函式建立物件,再逐一掛上屬性。
var student = new Object();
student.name = "xiao ming";
student.age = 20;
student.getName = function () {
alert(this.name);
}
熟悉物件字面值語法的人,多半會偏好下面這種更簡潔的寫法:
var student = {
name: "xiao hong",
age: 18,
getName: function () {
alert(this.name);
}
};
缺點:若要建立大量結構相似的物件,程式碼會大量重複。函式(方法或類別)存在的意義之一就是把共同邏輯抽取出來重用,而這種寫法完全沒有函式的影子,也就談不上重用。
工廠模式把「建立物件的過程」抽象成一個函式:呼叫它(進入工廠)並傳入相應參數(原材料),就得到一個物件(產品)。它解決了建立多個相似物件的問題。
function studentFactory(name,age) {
var student = new Object();
student.name = name;
student.age = age;
student.sayName = function () {
alert(this.name);
}
return student;
}
var p1 = studentFactory("ming", 20);
var p2 = studentFactory("hong", 18);
缺點:無法辨識物件型別。p1 instanceof Object 為真,但你沒辦法判斷它「具體是哪一種」物件。此時更好的解法是建立一個 Student 建構函式,讓所有物件都屬於 Student 型別。工廠模式並非不好,只是建構函式模式在型別資訊上更勝一籌。
function Student(name,age) {
this.name = name;
this.age = age;
this.sayName = function () {
alert(this.name);
}
}
var p3 = new Student("ming", 20);
var p4 = new Student("hong", 18);
alert(p3 instanceof Student);
alert(p3.sayName==p4.sayName); //false
缺點:每個物件都會重新建立自己的一份方法。像 sayName 這種功能完全相同的方法,卻在每個 instance 上各存一份(p3.sayName 與 p4.sayName 並不相等),造成不必要的記憶體浪費。
定義一個空函式,把所有屬性與方法掛到它的 prototype 上,如此一來所有物件都能共用。
function Student() {};
Student.prototype.name = "ming";
Student.prototype.age = 20;
Student.prototype.friends = ['qi'];
Student.prototype.sayName = function () {
alert(this.name);
};
缺點:並非所有屬性都適合共享。以 friends 為例,每位學生的朋友名單大不相同;若放在原型上,其中一人 push 之後,所有物件都會看到這個變化——這類「引用型別被共用」的問題在原型模式中特別棘手。
function Student(name, age, friends) {
this.name = name;
this.age = age;
this.friends = friends;
}
Student.prototype = {
constructor: Student,
sayName: function () {
alert(this.name);
}
};
總結:這是業界廣泛認可的做法,也是以上幾種之中的最佳解。自有的、每個物件該各自獨立的屬性放在建構函式裡;共用且只需一份的方法掛在原型上,兩者互補。注意重新賦值 prototype 之後務必補回 constructor,否則該屬性會指向 Object。
動態原型模式是組合模式的優化:共用屬性與方法只在第一次初始化時掛上原型,之後不再重複處理,省下每次 new 的判斷與賦值成本。
function Student(name, age) {
this.name = name;
this.age = age;
if ((typeof this.sayName) != "function") {
Student.prototype.sayName = function () {
alert(this.name);
}
}
}
var stu = new Person("ming", 20);
//alert(stu instanceof Student);
stu.sayName();
var stuNew = new Person("hong", 18);
//alert(stuNew instanceof Student);
stuNew.sayName();
建立多個物件時,sayName 只會初始化一次。(範例中的 Person 應相應改為 Student,否則會出現參照錯誤。)
穩妥建構函式模式則是另一個方向:不使用 this 與 new,物件除了 constructor 之外沒有任何公共屬性,外界只能讀取、無法改寫其內部狀態。
////穩妥建構函數模式
function Student(name, age) {
var o = new Object();
o.sayName = function () {
alert(name);
}
return o;
}
var stu = Student("ming", 21);
stu.sayName();
值得注意這裡的 sayName 直接閉包捕獲了參數 name,而非透過 this 取值,因此外部完全無法竄改。這種模式常用於安全性要求較高、或不希望物件被任意擴充的場合。
以上整理了几種常見的建立自訂物件方式。若你有更好的實踐,歡迎交流,本文持續更新。