Modern Javascript Development – Namespaces

By default, every object you create in JavaScript code gets dumped into a Global namespace. There is no syntactical method built into the language for declaring objects in a particular namespace. But there are some tricks that deal with scope that you can use to prevent name collisions.

Let’s review one method for creating objects in JavaScript and explore how to control the scope of their members..

	var foo = {
		version : "1",
		printHello : function() { document.write("Hello"); }
	};

This example creates a new object named “foo” in the Global namespace with a property called “version” and a method called “printHello”. Both the method and property are public. Functionally, the code is the same as this:

	var foo = function (){
		return {
			version : "1",
			printHello : function() { document.write("Hello"); }
		};
	}();

Let’s add a private member. (see here for a description of scope in JavaScript)

	var foo = function (){
		var private_hootie = "nyah nyah can't see me";
		return {
			version : "1",
			printHello : function() { document.write("Hello" + "<br/>"); },
		};
	}();

We can do the same for methods:

	var foo = function (){
		var private_hootie = "nyah nyah can't see me";
		function private_fuction() { document.write("private"); };
		return {
			version : "1",
			printHello : function() { document.write("Hello" + "<br/>"); },
			printHootie: function() { document.write(private_hootie + "<br/>"); }
		};
	}();

n.b. The printHootie method is able to access the private_hootie member.

Since everything in JavaScript is an object (functions, variables, everything), you can also nest the objects within an objects constructor:

	var com  = {
		lazycoder : {
			version : "1",
			printHello : function() {document.write("Hello" + "<br/>"); },
		}
	}

	com.lazycoder.printHello();

Now, you see the point of this little exercise. You can use objects to create namespaces within your code.

There’s nothing that says you have to use elaborate nesting schemes to create your namespaces though.

	var bar = {
		hootie: ""
	}
	
	bar.hootie = function() { document.write("hootie"); }

You can even extend existing namespaces.

	foo.bar = {
	    hootie: ""
	}
	
	foo.bar.hootie = function() { document.write("hootie"); }
	foo.printHello();
	//bar.hootie(); - undefined
	foo.bar.hootie();