Javascript namespace implementation

Todays web applications day by day implement ajax behaviour havily.
To implement that behaviour you need to write lots of javascript code.
Sometimes it becomes so talf to manage that javasript code.
In that situation we need to organize our code cleverly.

Then question raise how traditional oop language organize their code.
Well actually they create classes/structures/enumes/interfaces and that are grouped by namespace/package and it is alreay proven solution for code organization.

So why we donot follow oop languages style.
Well javascript does not support directly to declare namespace/package.
But we need to use namespace/package in javascript.
We need to follow same tricks like traditional oop.

In javascript everying is object(function, array etc) and no direct support of inheritance(means normally traditional oop language support.

So we will create objects to support namespace.

The code example is given bellow
================================
//first create a Manager, it will responsible to register namespaces.
var NamespaceManager = function(){

this.Register = function(name){
var parent = self; //set window reference
var arr = name.split('.');//consider user may use . relational operator

for(var index in arr){
var name = arr[index]; //retrive namespace name
parent[name] = new Object(); //create object.
parent = parent[name]; //reset parent object reference
}
}
}

//Actually NamespaceManager object's Register method will register our requested //namespace. under the hood it will create object(s).

//ok first we register our own namespace

var manager = new NamespaceManager();
obj.Register ('Root.Data.Xml'); //dummy namespace

//registration completed
//Now need to implemenet an object under that namespace.

Root.Data.Xml.Country = function(countryName){
this.CountryName = countryName,
this.Show = function(){
self.alert(this.CountryName);
}
};

//Object Country with 2 members is created. 1 property CountryName and 1 method Show //is inside that class.


//Now Need to call use that Country object under Root.Data.Xml namespace

var obj = new Root.Data.Xml.Show('Bangladesh');
obj.Show();

//and see it will show alert with 'Bangladesh'.

That way we can easily use namespace in javascript. But when we use javasript namespace we need to cosider some disadvantages

1. Complexity may little increase your code.
2. Performace may little decrease.

You obviouly consider some advantages too

1. Structured Code.
2. Unique classes
3. Easy integration with other projects.

So decission is yours based on your project context and other factors.

======
Thanks
======

No comments: