标签:
Although using the object constructor or an object literal are convenient ways to create single objects, there is an obvious downside: creating multiple objects with the same interface requires a lot of code duplication. To solve this problem, developers began using a variation of the factory pattern.
With no way to define classes in ECMAScript, developers created functions to encapsulate the creation of objects with specific interfaces, such as in this example:
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(){ 7 alert(this.name); 8 }; 9 return o; 10 } 11 12 var person1 = new Person("Nicholas", 29, "Software Engineer"); 13 14 var person2 = new Person("Greg", 27, "Doctor");
Though this solved the problem of creating multiple similar objects, the factory pattern didn‘t address the issue of object identification(what type of object an object is).
标签:
原文地址:http://www.cnblogs.com/linxd/p/4488826.html