Monday, August 18, 2008

Namespacing in JavaScript

Namespacing, in general, allows one to provide a context for the content to be declared in one's code. It helps resolve same name ambiguities by having variables, functions and even objects residing in different namespaces. JavaScript, unlike Java, does not have the "namespace" keyword as part of its standard list.

Now, there are different ways of defining namespaces in JS. The root namespace's name should be as unique as possible and should generally be having application scope, but there is no restriction present and can be named according to one's preferences. Before delving into more details, I think an example will give all a better idea on this. So, here goes:

var MyNameSpace = {};

MyNameSpace.MyClass = function(str){
this.name = str;
this.alertClassName = function(){ alert(this.name); }
}

//usage
with(MyNameSpace){
var myObject = new MyClass("Class1");
myObject.alertClassName();
}

Here, an object called "MyNameSpace" is created in the global(window) scope of things. Now, one must ensure that only one root namespace exists. There are a variety of ways one can do so but I shall not delve into those methods at this time.

The class declaration basically creates a property of the "MyNameSpace" object and hence declaration of any object created from this class must use the root namespace before an instance can be created. This also encapsulates the class("MyClass") and ties it to the root namespace and hence prevents name conflicts with any other included javascript classes or variables that may also have the same name "MyClass".

There exists other ways in which namespaces can be declared but I feel the example above is easiest to understand and implement. In case you feel otherwise, I'd like to know why.

Cheers.

No comments: