Since any variable declared in the code automatically becomes a global variable residing on the main window object,
accidental overriding of variables could occur. Further more, code maintenance and modular components are hard to implement.
The solution is using name spaces and JavaScript modules. Nested modules can also be easily created.
- Name spaces are implemented using JavaScript objects.
- Modules are achieved using JavaScript immediate functions.
Here is a simple example:
var myAppNS;
(function (myAppNS) {
myAppNS.prop = value;
myAppNS.func = function() {
// do some stuff...
};
} (myAppNS = myAppNS || {}));
Check out this jsfiddle to see an example.
For nested modules and nested name spaces - check out this plnkr.
No comments:
Post a Comment