NameSpaces In JavaScript

Posted By : Akhil Dhiman | 01-Jul-2014

What are Namespaces in JavaScript

Namespaces are the methods to avoid collisions of global variables in JavaScript. In javascript there are no pre defined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. It is the technique that is used put each variable to a unique object that can be uniquely identify. It is the prefix to attached in front of function that can be called anywhere in any script file and with the use of it we can identify that the function/variable belongs to which namespace.

Register a NameSpace

Following is the function to register a name space

 //Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}
 

To register a Namespace just call the above function with the argument as name space separated by .(dot).
For Example
Let your application name is oodles. You can make a namespace by following method.

 registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;
 

Basically it will create your NameSpaces structure like below in backend:

 var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};
 

In the above function you have register a namespace calles "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.
These variables are nothing but an alias to Intializing the namespace.
Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

 $OHU.initialization = function(){
    //Your Code Here
};
 

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

 $OHU.initialization();
 

Similarly, with the another NameSpaces.

About Author

Author Image
Akhil Dhiman

Akhil is an iPhone and Android application developer with experience in PhoneGap and Swift(Native iOS). Akhil has good experience working with JavaScript, jQuery and Underscore as well.

Request for Proposal

Name is required

Comment is required

Sending message..