JS Modular programming, has become an urgent need. Ideally, developers only need to implement core business logic, and others can load modules that others have already written.
However, JS is not a modular programming language, it does not support classes, so there is no strict module. In order to achieve modularity, class modularity came into being.
1, the original wording:
A module is a set of methods for implementing a specific function.
Just put the different functions together simply, is a module.
Eg:
function T1 () {
//...
}
Function T2 () {
//...
}
Cons: Polluting global variables, there is no guarantee that the variable name conflicts with other modules, and there is no direct relationship between the module members.
2. Object wording:
In order to solve the defect of the original writing, the module can be written as an object, and all the module members are placed inside the object.
Eg:
var module1=new Object ({
num:0,
Fn1:function () {
//...
},
Fn2:function () {
//...
}
});
BUG: Global variables can be arbitrarily rewritten.
3. Immediately execute function notation
Executing functions immediately can achieve the purpose of not exposing private members.
Eg:
var class1= (function () {
var num=0;
var fn1=function () {
//...
};
var fn2=function () {
//...
};
return {
M1:FN1,
M2:FN2,
};
})();
This kind of writing is the normal way of JS modularization.
4. Magnification mode
If a module is large and needs to be divided into multiple parts, the magnification mode must be used.
Eg:
var class2= (function (c1) {
C1.fn3=function () {
//...
}
}) (Class1);
5, implement call external global variables, Jquery etc.
Independence is an important feature of modularity, and it is best not to interact directly with other external members within the module.
In order to implement a modular call to an external global member, the other variables must be shown to be input into the module.
Eg:
var class1= (function (Jq,ya) {
//...
}) (Jquery,yahoo);
The above module implements the jquery and Yui libraries. The purpose of this is to ensure the independence of the modules, and also make the dependencies between the modules become apparent.
JavaScript Modular Programming-notation