码迷,mamicode.com
首页 > 其他好文 > 详细

Object Creation

时间:2015-05-08 21:47:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

  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.

 

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");
View Code

 

  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). 

 

Object Creation

标签:

原文地址:http://www.cnblogs.com/linxd/p/4488826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!