First, the original wording
A module is a set of methods for implementing a specific function.
Simply put the different functions (and the variables that record the state) together, even if it is a module.
function M1 () {//...} function m2 () {//...}
The above functions M1 () and M2 () to form a module. When used, call directly on the line.
The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.
Ii. the wording of the object
In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this object.
var module1 = new Object ({_count:0, m1:function () {//...}, M2:function () {//...} });
The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object.
However, such a notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter.
Iii. immediate execution of function notation
Using the Execute functions now (immediately-invoked function Expression,iife), you can achieve the purpose of not exposing private members.
var Module1 = (function () {var _count = 0; var m1 = function () {//...}; var m2 = function () {//...}; return {m1:m1, m2:m2}; })();
Using the notation above, the external code cannot read the internal _count variable.
Console.info (Module1._count); Undefined
Module1 is the basic way of writing JavaScript modules.
JavaScript Modular Programming