工厂模式
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("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
优点:避免创建多个对象时的重复代码问题
缺点:无法解决对象识别问题(不知道一个对象的类型)
构造函数模式
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");
alert(person1.constructor == Person); // true
alert(person1 instanceof Person); // true
构造函数可以当作普通函数一样使用,例如不使用new关键字:
Person("Greg", 27, "Doctor");// 添加到window
window.sayName(); // "Greg"
也可以在另一个对象作用域中使用:
var o = new Object();// 在另一个对象的作用域中调用
Person.call(o, "Kristen", 25, "Nurse");
o.sayName();
缺点:每个方法都会在实例上被创建一遍,sayName()是Function的实例,因此person1的sayName和person2的sayName不是同一个对象。解决方法是把sayName()放在外面,但是破坏了封装性。
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("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
alert(person1.constructor == Person);
alert(person1 instanceof Person);
alert(person1.sayName === person2.sayName);// true
原型模式
function Person() {
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function () {
alert(this.name);
}
var person1 = new Person();
person1.sayName();
var person2 = new Person();
person2.sayName();
alert(person1.sayName === person2.sayName);// true