Thursday, May 3, 2012

Javascript Constructor & Namespacing

Namespacing is an obvious requirement for any JS applications in the enterprise world - apps. with several functions & data sets. Keeping data/functions i.e., objects in the global namespace would otherwise require being very creative with var names.
The following code demonstrates how to create a name space as well as constructors for JS Objects.

var a = {};
a.b = {};
a.b.C = function(){
    console.log("Constructor called!!");
    this.value="a.b.C";
    this.toString = function(){return this.value};
}

//console.log(b) // ReferenceError: b is not defined
console.log(a.b) // Object { C=function()}

var aa = new a.b.C();
console.log("Value: " + aa.toString()); // Constructor called!! 
                                        // Value: a.b.C