首页 > 其他 > 详细

Object Creation

时间:2015-05-08 21:45:19      阅读:255      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!