Monday 5 July 2010

JavaScript Namespace Example

I am currently working on a personal project that is getting kinda big in regards to the size of the JavaScript code. So it is time to organize the code using JavaScript namespaces. Since I could not remember how I did this in the past, time to create an example! :)



This namespace example puts almost all of the JavaScript code in the Blue namespace. The key point I was missing was the declaration of the space. For example, the namespace can be defined using JSON like this.



   1:var Blue = {
2: obj:{}, // Objects
3: gen:{} // General Functions
4:}
5:
Note: Line Numbers are unrelated to the actual position of the code in the example



The 3 letter abbreviations separate functions and objects into something similar to Java packages. The package names should be spelled out, but I'm lazy so 3 letter abbreviations for me.



Declare your instance variables and methods with code similar to this.

   1:Blue.obj.List = function(newName){
2: this.listName = newName;
3: this.itemArr = new Array();
4:}
5:
6:
7:Blue.obj.List.prototype.addItem = function(newItem){
8: this.itemArr.push(newItem);
9:}
10:
11:Blue.obj.List.prototype.deleteItem = function(index){
12: this.itemArr.splice(item);
13:}
14:


It may seem a bit wordy or maybe a bit of overkill at first. However, in the end your code will be much easier to maintain if you use this approach.

No comments:

Post a Comment