1、标准创建对象模式
1 var person = new Object(); 2 person.name = "Nicholas"; 3 person.age = 29; 4 person.job = "Software Engineer"; 5 person.sayName = function(){alert(this.name);};
2、字面量模式
1 var person = { 2 name: "Nicholas", 3 age: 29, 4 job: "Software Engineer", 5 sayName: function(){alert(this.name);} 6 };
3、工厂模式
1 function createPerson(name, age, job){ 2 var o = new Object(); 3 o.name = name; 4 o.age = age; 5 o.job = job; 6 o.sayName = function(){alert(this.name);}; 7 return o; 8 } 9 var person1 = createPerson("Nicholas", 29, "Software Engineer"); 10 var person2 = createPerson("Greg", 27, "Doctor");
4、构造函数模式
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.sayName = function(){alert(this.name);}; 6 } 7 var person1 = new Person("Nicholas", 29, "Software Engineer"); 8 var person2 = new Person("Greg", 27, "Doctor");
5、原型模式
1 function Person(){} 2 Person.prototype.name = "Nicholas"; 3 Person.prototype.age = 29; 4 Person.prototype.job = "Software Engineer"; 5 Person.prototype.sayName = function(){alert(this.name);}; 6 var person1 = new Person(); 7 person1.sayName(); //"Nicholas" 8 var person2 = new Person(); 9 person2.sayName(); //"Nicholas" 10 alert(person1.sayName == person2.sayName); //true
6、组合构造函数和原型模式
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.friends = ["Shelby", "Court"]; 6 } 7 Person.prototype = { 8 constructor : Person, 9 sayName : function(){alert(this.name);} 10 } 11 var person1 = new Person("Nicholas", 29, "Software Engineer"); 12 var person2 = new Person("Greg", 27, "Doctor"); 13 person1.friends.push("Van"); 14 alert(person1.friends); //"Shelby,Count,Van" 15 alert(person2.friends); //"Shelby,Count" 16 alert(person1.friends === person2.friends); //false 17 alert(person1.sayName === person2.sayName); //true
7、动态原型模式(这里只在 sayName()方法不存在的情况下,才会将它添加到原型中。)
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 if (typeof this.sayName != "function"){ 6 Person.prototype.sayName = function(){alert(this.name);}; 7 } 8 } 9 var friend = new Person("Nicholas", 29, "Software Engineer"); 10 friend.sayName();
8、寄生构造函数模式(除了使用 new 操作符并把使用的包装函数叫做构造函数之外,这个模式跟工厂模式其实是一模一样的。)
1 function Person(name, age, job){ 2 var o = new Object(); 3 o.name = name; 4 o.age = age; 5 o.job = job; 6 o.sayName = function(){alert(this.name);}; 7 return o; 8 } 9 var friend = new Person("Nicholas", 29, "Software Engineer"); 10 friend.sayName(); //"Nicholas"
9、稳妥构造函数模式(一是新创建对象的实例方法不引用 this;二是不使用 new 操作符调用构造函数)
function Person(name, age, job){ var o = new Object(); o.sayName = function(){alert(name);}; return o; } var friend = Person("Nicholas", 29, "Software Engineer"); friend.sayName(); //"Nicholas"