1. 工厂模式
1 function createPerson(name, age) 2 { 3 var obj = {}; 4 obj.name = name; 5 obj.age = age; 6 obj.getName = function(){ 7 return this.name; 8 }; 9 return obj; 10 } 11 12 var person = createPerson('leon', 30);
2. 构造函数模式
1 function Person(name, age) 2 { 3 this.name = name; 4 this.age = age; 5 this.getName = function(){ 6 return this.name; 7 }; 8 } 9 10 var person = new Person('leon', 30 );
3. 原型模式 (多个对象实例之间共享属性值和方法)
1 function Person(){ 2 3 } 4 5 Person.prototype = { 6 constructor: Person, 7 name: 'leon', 8 age: 30, 9 getName: function(){ 10 return this.name; 11 } 12 }; 13 14 var person = new Person();
4. 组合构造函数和原型模式 (构造函数模式与原型模式的结合,属性在构造函数中进行定义,方法在原型中定义)
1 function Person(name, age) 2 { 3 this.name = name; 4 this.age = age; 5 } 6 7 Person.prototype = { 8 constructor: Person, 9 getName : function(){ 10 return this.name; 11 } 12 }; 13 14 var person = new Person('leon', 30 );
5.动态原型模式 (原型模式的改进为了更好的体现封装)
1 function Person(name, age) 2 { 3 this.name = name; 4 this.age = age; 5 if( typeof this.getName != 'function'){ 6 Person.prototype.getName = function(){ 7 return this.name; 8 } 9 } 10 }
6. 寄生构造函数模式 (工厂模式与构造函数的结合)
1 function Person(name, age) 2 { 3 var obj = {}; 4 obj.name = name; 5 obj.age = age; 6 obj.getName = function(){ 7 return this.name; 8 }; 9 return obj; 10 } 11 12 var person = new Person('leon', 30);
7. 稳妥构造函数模式 (工厂模式的安全版,无公共属性,方法中无this引用)
1 function Person(name, age) 2 { 3 var obj = {}; 4 var name = name; 5 var age = age; 6 obj.getName = function(){ 7 return name; 8 }; 9 return obj; 10 } 11 12 var person = Person('leon', 30);