/*1、工厂模式*/
function createPerson(name,age,job) {
var o = new object();
o.name = name;
o.age = age;
o.job = job;
o.setName = function(newName) {
this.name = newName;
};
return o;
}
var person1 = createPerson("zcj", 21, "Soft Engineer");
/*
问题:只能创建多个相似的对象,不能识别对象
*/
/*2、构造函数模式*/
function Person(name,age,job) {
this.name = name;
this.age = age;
this.job = job;
this.setName = function(newName) {
this.name = newName;
}
}
var person1 = new Person("zcj", 21, "Soft Engineer");
/*
问题:每个方法都要在实例上重新创建一遍
*/
/*3、原型模式*/
function Person() {
} person.prototype.name = "zcj";
person.prototype.age = 21;
person.prototype.job = "Soft Engineer";
person.prototype.sayName = function() {
alert(this.name);
}; var person1 = new Person();
var person2 = new Person();
alert(person1.sayName == person2.sayName); //true person1.name = "Greg";
alert(person1.name); //"Greg"
alert(person2.name); //"zcj" delete person1.name;
alert(person1.name); //"zcj"
/*
问题:所有实例在默认情况下取得相同的属性值;对于引用类型的属性,为所有实例共享(这是不期望的)
*/
/*4、组合使用构造函数模式和原型模式*/
function Person(name,age,job) {
this.name = name;
this.age = age;
this.job = job;
friends = ["Shelby","Court"]
}
Person.prototype = {
constructor:Person,
sayName: function() {
alert(this.name);
}
}
var person1 = new Person("zcj",21,"Soft Engineer");
var person2 = new Person("Gerg",27,"Doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shellby,Court,Van"
alert(person2.friends); //"Shellby,Court"
alert(person1.friends === person2.friends); //false
alert(person1.sayName === person2.sayName); //true
/*
说明:使用最广泛,认同度最高的创建自定义类型的方法
*/
/*5、动态原型模式*/
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);
};
}
}
var friend = new Person("zcj", 21, "Soft Engineer");
friend.sayName();
/*
说明:将所有信息封装在构造函数中,通过检查某个应该存在的方法是否有效,决定是否需要初始化
*/
/*6、寄生构造函数模式*/
function Person(name,age,job) {
var o = new object();
o.name = name;
o.age = age;
o.job = job;
o.setName = function(newName) {
this.name = newName;
};
return o;
}
var person1 = new Person("zcj", 21, "Soft Engineer");
person1.setName("Gerg");
alert(person1.name); //"Gerg"
/*
说明:与工厂模式区别:1、实例化对象要使用new;2、改包装函数为构造函数(函数名第一个字母大写)
*/
/*7、稳妥构造函数*/
function Person(name,age,job) {
var o = new object();
//创建私有变量和函数
var privateVariable = 10;
function privateFunction() {
return false;
} //添加特权方法
o.sayName = function() {
alert(name);
};
//返回对象
return o;
}
/*
这种模式创建的对象中,除了sayName方法外,没有其他方法访问name属性
*/