面向对象JS编程(一)——创建对象
1.普通模式
var person = new Object();
person.name = "Laughing";
person.age = 28;
person.job = "Software Engineer";
peron.sayName = function(){
alert(this.name);
};
person.sayName();
缺点:创建多个对象时,会产生大量的重复代码。
2.工厂模式
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 = new Person("Laughing", 28, "Software Enginner");
var person2 = new Person("Greg", 27, "Doctor");
缺点:无法识别对象的类型。
3.构造函数模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person("Laughing", 28, "Software Enginner");
var person2 = new Person("Greg", 27, "Doctor");
优点:可以使用instanceof判断对象类型,即alert(person1 instanceof Person); //true
缺点:每个方法都需要在每个实例上重新创建一遍。
4.原型模式
function Person(){
}
Person.prototype.name = "Laughing";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
alert(person1.sayName == person2.sayName); //true
缺点:对于包含引用类型值的属性,共享非常不合适。如:
function Person(){
}
//更简单的原型模式
Person.prototype = {
constructor: Person, //重新指定constructor
name : "Laughing",
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" 期望是 "Shelby, Court"
5.原型构造模式
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("Laughing", 28, "Software Engineer");
var person2 = new Person("Greg", 29, "Doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shelby, Count, Van"
alert(person2.friends); //"Shelby, Count"