JavaScript中創建對象的方式有多種,這裏只介紹三種:構造函數模式、原型模式、組合使用構造函數模式和原型模式(推薦)
1、構造函數模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person("Nicholas", 29, "software engineer");
var person2 = new Person("Greg", 27, "doctor");
缺點:使用構造函數的問題就是每個方法都要在新創建的實例上重新創建一遍。
2、原型模式
function Person(){}
Person.prototype = {
constructor : Person,
name : "Nicholas",
age : 29,
job : "software engineer",
friends : ["Shelby","Court"],
sayName : function(){
alert(this.name);
}
};
var person1 = new Person();
var person2 = new Person();
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Court,Van"
alert(person2.friends); //"Shelby,Court,Van"
alert(person1.friends === person2.friends); //true
缺點:使用原型方式的一個突出問題在於如果包含引用類型的屬性(Person.friends),那麼某一個對象修改這個屬性值,會影響到其它對象。
3、組合使用構造函數模式和原型模式(推薦方式)
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
}
Person.prototype = {
constructor : Person,
sayName : function(){
alert(this.name);
}
};
var person1 = new Person("Nicholas", 29, "software engineer");
var person2 = new Person("Greg", 27, "doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Court,Van"
alert(person2.friends); //"Shelby,Court"
alert(person1.friends === person2.friends); //false
alert(person1.sayName === person2.sayName); //true
JS創建對象的方式除了以上三種,還有其它多種方式,請參考文章http://www.cnblogs.com/tiwlin/archive/2009/08/06/1540161.html