1 /**
2 * Created by 2016 on 2016/6/4.
3 */
4 function Box(){
5 var obj = new obj();
6 obj.name = "Lee";
7 obj.run = function(){
8 return this.name+"run";
9 };
10 return obj;
11 }
12 var B = Box();
13 //工厂模式创建对象 在对象中创建obj,在最后返回obj对象
14
15
16
17 function Box(){
18 this.name = "Lee";
19 this.run = function(){
20 return this.name+"run";
21 };
22 }
23 var B = new Box();
24 //构造函数模式 使用new运算符创建对象
25
26
27
28 function Box(){};
29 Box.prototype.name = "Lee";
30 Box.prototype.run = function(){
31 return this.name+"run";
32 };
33
34 var B = new Box();
35 //原型模式创建,prototype为原型属性。
36 //优点:方法共享,缺点:属性共享
37
38
39
40 function Box(){};
41 Box.prototype = {
42 constructor:Box,//强制指向Box原型,否则指向object
43 name:"Lee",
44 run:function(){
45 return this.name+"run";
46 }
47 };
48 var B = new Box();
49 //原型模式,字面量形式创建。这里不能重写字面量,会导致之前的连接断开
50 //缺点:无法传递参数,所有属性共享
51
52
53
54 function Box(){
55 this.name = "Lee";
56 Box.prototype.run = function(){
57 return this.name+"run";
58 };
59 };
60 var B = new Box();
61 //原型+构造函数模式创建,这里每一个实例的run都会初始化一次,所以可以使用动态的原型+构造
62 //函数模式
63
64 function Box(){
65 this.name = "Lee";
66 if(typeof Box.prototype.run != "function"){
67 Box.prototype.run = function(){
68 return this.name+"run";
69 };
70 }
71
72 };
73 var B = new Box();
74
75 //动态创建。这里的run只会被初始化一次,并且方法是共享的,节省内存
76
77 //创建对象的方法有很多,使用动态的原型+构造函数模式创建比较好。
78 //实例属性独立,方法共享。
function Box(){
var obj = new Array();
obj.name = "Lee";
obj.run = function(){
return this.name+"run";
};
return obj;
}
var B = new Box();
//寄生构造函数模式 除了使用new操作符创建对象之外,和工厂模式是一致的