A function can be seen as a behavior or a method, the following two is two methods ———— two modules, but this will pollute the global variables, there is no guarantee that the other modules do not conflict with the variable name, and the module members do not see a direct relationship.
function M1 () {
//...
}
function m2 () {
//...
}
In order to solve the above method, the module can be written as an object, and all the module members are put into this object.
var module1 = new Object ({
_count:0,
M1:function () {
//...
},
M2:function () {
//...
}
});
The call to M1 here is directly module1.m1 (); Yes, but then the code can be rewritten.
If you don't let the code be rewritten here,
var Module1 = (function () {
var _count = 0;
var m1 = function () {
//...
};
var m2 = function () {
//...
};
return {
M1:M1,
M2:m2
};
})();
With the closure of the wording, so that there is no way outside to read the code inside,
Console.info (Module1._count); Undefined
If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "magnification mode" (augmentation).
var Module1 = (function (mod) {
MOD.M3 = function () {
//...
};
return mod;
}) (Module1);
The code above adds a new method M3 () to the Module1 module and then returns the new Module1 module.
In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded first. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".
var Module1 = (function (mod) {
//...
return mod;
}) (Window.module1 | | {});
In this way, the passed in can be an empty object.
JavaScript Modular Programming