a simple example about javascript module.

moduleVariable= moduleVariable || {};
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
moduleVariable.planA=(function(){
// define some variable privately , it can only be used within this function.
var someVariable={
a : 'a',
b : 'b',
c : 'c'
};
//define a couple of object to include some functions. one for privately , the other one for public.
var private = {};
var public = {};
/*this is private method below , due to the object private can only be visited in this function , so the method belong to
this object can only be visited in this function*/
private.functionA=function(){
/*Do something*/
console.log(someVariable.a);// it can visite someVariable;
}
private.functionB=function(){
/*Do something else*/
console.log(private.functionA);// it can visite private.functionA;
}
public.init=function(){
var a=someVariable.a;
private.functionA();
private.functionB();//it can visite variables and functions in this function.
}
return public; //在最后我们返回了public,那么在外部moduleVariable.planA就等于public,moduleVariable.planA可以访问到public的init方法
//但是其他所有的变量,私有方法(private),都没有暴露给外部,只在public的init()方法中可以被使用
})();
$(document).ready(function(){
moduleVariable.planA.init();//Be invoked here.
})