同樣是「造一個物件」,寫法不同,帶來的彈性與問題也完全不同。以下從最原始的寫法一路談到實務上最推薦的混合模式。
var person = new Object();
person.name = "RuiLiang";
person.age = 30;
person.job = "Teacher";
person.sayName = function () {
alert(this.name);
};
person.sayName();
問題顯而易見:要造十個 person 就得寫十遍。
把建立過程包進函式裡,用參數傳入差異部分。
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
alert(this.name);
};
return o;
}
var person1 = createPerson("阿亮", 30, "教師");
var person2 = createPerson("俊俊", 24, "待業");
person1.sayName(); // "阿亮"
person2.sayName(); // "俊俊"
缺點是無法識別物件的型別——所有產品看起來都只是一個普通 Object。
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName;
}
function sayName() {
alert(this.name);
}
var person1 = new Person("阿亮", 30, "教師");
var person2 = new Person("俊俊", 24, "待業");
用 new 呼叫後,物件會帶有 constructor 指向 Person,型別因此可辨識。缺點是每個實例都有一份自己的函式副本,浪費記憶體。
把共用的成員掛到 prototype 上,所有實例共享。
function Person() {}
Person.prototype.name = "ALiang";
Person.prototype.age = 30;
Person.prototype.job = "Teacher";
Person.prototype.sayName = function () {
alert(this.name);
};
缺點是連「本該各自獨立」的屬性也被共享了,特別是陣列與物件,一個實例改動會影響全部。
hasOwnProperty() 檢查屬性是否屬於實例本身:
person1.hasOwnProperty("name"); // name 是 person1 自己的屬性嗎
in 操作符則只要屬性存在就回傳 true,不論在實例還是在原型上:
alert("name" in person1);
把兩者組合起來,就能判斷屬性是否只存在於原型:
function hasPrototypeProperty(object, name) {
return !object.hasOwnProperty(name) && (name in object);
}
var person = new Person();
alert(hasPrototypeProperty(person, "name")); // true
person.name = "Grey"; // 在實例上建立同名屬性,遮蔽了原型
alert(hasPrototypeProperty(person, "name")); // false
isPrototypeOf() 用來判斷某物件是否出現在另一個物件的原型鏈上:
object1.isPrototypeOf(object2);
若 object2 的原型鏈中包含 object1 就回傳 true,否則 false。
也可以用字面量一次重寫整個原型:
function Person() {}
Person.prototype = {
constructor: Person,
name: "ALiang",
age: 30,
job: "Teacher",
sayName: function () {
alert(this.name);
}
};
這裡務必手動補上 constructor,否則它會被重設為 Object。
實務上最廣泛採用的方案:屬性用建構函式(各自獨立),方法用原型(共享復用)。
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ["xuyun", "wuxueming"];
}
Person.prototype = {
constructor: Person,
sayName: function () {
alert(this.name);
}
};
var person1 = new Person("ALiang", 30, "Teacher");
var person2 = new Person("ZuNan", 26, "Teacher");
person1.friends.push("JunJun");
alert(person1.friends); // xuyun,wuxueming,JunJun
alert(person2.friends); // xuyun,wuxueming,不受影響
把所有成員都放在建構函式裡,只在第一次執行時初始化原型,兼顧整潔與效率。
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function") {
Person.prototype.sayName = function () {
alert(this.name);
};
}
}
這裡要注意:原型屬性不能用字面量方式一次賦值,因為那會在 if 之外執行,反而每次都重新建立原型。
寄生建構函式模式:在建構函式中回傳另一個物件,通常用於想為既有的原生建構函式(如 Array)增添方法的特殊情境。
穩妥建構函式模式:不使用 this、不使用 new,只回傳物件,且物件上沒有任何對外的屬性參考。適合在安全沙箱環境中使用。
若你在寫 ES6 之後的專案,直接用 class 搭配 extends,底層就是混合模式的標準化版本,能省下不少手動設定的功夫。