一、工厂模式:用函数来封装以特定接口创建对象
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("wei",25,"software");
var person2 = createPerson("bu",25,"software");
二、构造函数模式:我们可以创建自定义个构造函数,从而定义自定义类型的属性和方法。
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
}
}
var person1 = new Person("wei",25,"software");
var person2 = new Person("bu",25,"software");
三、原型模式:
function Person(){
}
Person.prototype.name = "wei";
Person.prototype.age = 27;
Person.prototype.job = "Software";
Person.prototype.sayName = function(){
alert(this.name);
}
var person1 = new Person();
person1.sayName(); //"wei"
var person2 = new Person();
person2.sayName(); //"wei"
alert(person1.sayName == person2.sayName);
四、组合使用构造函数模式和原型模式
function Person(name, age){
this.name = name;
this.age = age;
this.friends = ["乾隆","康熙"];
}
Person.prototype = {
constructor:Person,
sayName:function(){
alert(this.name);
}
}
var person1 = new Person("wei",29);
var person2 = new Person("bu",25);
person1.friends.push("嬴政");
console.log(person1.friends); //["乾隆", "康熙", "嬴政"]
console.log(person2.friends); //["乾隆", "康熙"]
console.log(person1.friends === person2.friends); //false
console.log(person1.sayName === person2.sayName); //true