Namespaces in JS

by Alon Rotem

JavaScript

//Demo: Namespaces in JS.
//Alon Rotem, 2016.

//A nested JSON object acts as a wrapper namespace, since its internal parts
//can be accessed only through dotted object properties notation.
//The internal parts, of course can be object constructors too.
var KPMG = {
	RefArc : {
  	Tools : {
			    JsObject : function()
          {
          	var callCounter = 0;
          	this.SayHello = function(name)
            {
              callCounter++;
              alert("Hello, " + name + " (Called " + callCounter+ " times...)");
            }
          }
    }
  }
};
var obj = new KPMG.RefArc.Tools.JsObject();
obj.SayHello("Alon");
obj.SayHello("Tom");

//------------------------------------------------------------------

//Another opton for notation:
//Starting with an empty object, adding a parent class, and a child class.
//Making the child call the parent's constructor, 
//and adding the child class to the parent's prototype, creates an inheritance hierarchy.
var KPMGns = {};
KPMGns.ParentClass = function(someValue) {
    this.val = someValue;
    this.alertValue = function() {
        alert("Hello! Value is " + this.val);
    }
}
KPMGns.Childclass = function(someValue) {
    KPMGns.ParentClass.call(this, someValue);
    this.alertChild = function() {
    	alert("Hello from child class!");
    }
}
KPMGns.Childclass.prototype = new KPMGns.ParentClass;

//Now you can create an object of the inherited class, 
//call methods from both the parent or the child.
var obj2 = new KPMGns.Childclass(3);
obj2.alertValue();
obj2.alertChild();