Tuesday, June 11, 2013

JavaScript Name Spaces and Modules

An important concept of modular JavaScript is name spaces usage. 
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

About Me

My photo
I've been developing Internet and rich-media application for 15 years. In my work I emphasis usability and best user experience as well as sleek design. My main expertise are JavaScript, Flex and Flash.

Followers