Javascript Tutorial – Namespaces

Namespaces can be a powerful tool for code organization and conflict avoidance. Unfortunately, Javascript does not have native support for this extremely useful construct. That being said, the language’s flexibility allows us to create a facsimile that works quite well.

Namespace Declaration

We’re going to use objects to simulate namespaces. At the top of each file where you want to include and use a namespace, add the following line.

var myNamespace = myNamespace || {};

This line will either create a new object to hold our namespace or return the existing one. Technically this line only needs to be added to the top of the first script file included on the page, but it’s much easier (and better for testing) to just add it to every file.

Usage

Now that we have an instance of an empty object, all we have to do is add objects to it.

var myNamespace = myNamespace || {};

// Declare a new object.
myNamespace.MyObject = function() {
  this.myProperty = "someValue";
};

// Create an instance of the object.
var myInstance = new myNamespace.MyObject();

console.log(myInstance.myProperty); // someValue

As you can see, by assigning a function (class) to the property myNamespace.MyObject, we’ve essentially simulated adding an object to a namespace. Any number of objects can be added to our namespace like this, and since MyObject is now inside myNamespace, we don’t have worry about conflicting with all the other Javascript that might be running on the page.

And there you have it – an extremely simple solution to namespacing your Javascript code. It’s probably a good idea to use namespaces whenever possible since you never know whether or not a type already exists that you’re about to redefine. If you’re building a public library, like jQuery, then it should be an absolute requirement.

Want to learn more about Javascript? Check out these great books:

Leave a Reply

Your email address will not be published. Required fields are marked *