In some large projects are often used to the module, here, we will understand what is the module mode. The simplest method of module mode will be used by everyone, as shown below:
var a = { b:1, c:2 }
The direct amount of such an object can already represent the definition of a module. But here's the problem: the B and C properties inside a object are public, which means we can arbitrarily change the value outside. The modular design requires that we try our best to implement the values and methods in the module without being externally altered to form an independent or private environment. So we can write this:
var count = (function (window, undefined) {var total = 0;//Private member variable var c = function (q) {//private method, Closure function total++;} return {count:c//exposed private method,};}) (window, undefined)
As you can see, Count finally accepts a self-polygon amount returned by the anonymous function, where the Count method is also the private C's public method alias is the closure function that contains the context within the anonymous function, through which we can change the value of total to achieve total privatization. We can change the value of total in this way.
Count.count ();//So the total value is incremented by 1
In the example above we can see some features of the module pattern:
- Modular, REUSABLE
- Encapsulates variables and function, and the global namaspace does not touch, loosely coupled
- Only exposes methods that are available to public, and all other private methods are hidden.
Modular design is often referenced in large applications. With some module loaders, and AMD specifications, we can organize projects in order to achieve maintainable, high-efficiency code.
Javacript design mode-----Module mode