- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModule.js
More file actions
Latest commit
131 lines (100 loc) · 2.55 KB
/
Copy pathModule.js
File metadata and controls
131 lines (100 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Module 模块模式
* Module模式用于进一步模拟类的概念,通过这种方式,能够使一个单独的对象拥有公有/私有方法和变量,
从而屏蔽来自全局作用域的特殊部分
* Module 使用闭包封装 私有 状态和组织
* 降低与其他脚本的命名冲突
* 缺点:由于访问公有和私有成员的方式不同,当想改变可见性时,必须修改每一个使用该成员的地方
*/
//example1
vartestModule=(function(){
varcounter=0;
return{
incrementCounter : function(){
return++counter;
},
resetCounter : function(){
console.log("counter value prior to reset: "+counter);
counter=0;
}
}
})();
testModule.incrementCounter();
testModule.resetCounter();
console.log(testModule.counter);//undefined
//example2
varmyNamespace=(function(){
varmyPrivateVar=0;//私有计数器变量
varmyprivateMethod=function(foo){//私有函数
console.log(foo);
};
return{
myPublicVar : 'foo',//公有变量
myPublicFunction : function(bar){//公有函数
myPrivateVar++;
myprivareMethod(bar);
}
};
})();
//example3
varbasketModule=(function(){
varbasket=[];
functiondoSomethingPrivate(){}
functiondoSomethingElsePrivate(){}
return{
addItem : function(values){
basket.push(values);
},
getItemCount : function(){
returnbasket.length;
},
doSomething : doSomethingPrivate,
getTotal : function(){
varitemCount=this.getItemCount(),
total=0;
while(itemCount--){
total+=basket[itemCount].price;
}
returntotal;
}
}
})();
basketModule.addItem({
item : "bread",
price : 0.5
});
basketModule.addItem({
item : "butter",
price : 0.3
});
console.log(basketModule.getItemCount());// 2
console.log(basketModule.getTotal());// 0.8
console.log(basketModule.basket);//undefined
console.log(basket);// ERROR: not defined
// Module 模式变化
// 引入,将全局变量作为参数传递给模块的匿名函数
varmyModule=(function(jQ,_){//可以在模块中使用别名
functionprivateMethod1(){
jQ(".container").html("test");
}
functionprivateMethod2(){
console.log(_.min([10,5,100,2,1000]));
}
return{
publicMethod : function(){
privateMethod1();
}
}
})(jQuery,_);
myModule.publicMethod();
// 引出
varmyModule=(function(){//全局模块
varmodule={},
privateVar="Hello World";
functionprivateMethod(){}
module.publicProperty="Foobar";
module.publicMethod=function(){
console.log(privateVar);
};
returnmodule;//返回模块对象
})();