Home > AJAX, JavaScript, Software > Namespacing Your JavaScript

Namespacing Your JavaScript

March 17th, 2008

Namespacing your JavaScript is critical for sites that make heavy use of JavaScript, or sites that use any the JavaScript AJAX libraries (Scriptaculous, ASP.NET AJAX Client Side, YUI, JQuery, …). It’s also a great defensive programming technique – this is another post on JavaScript techniques that I’ve found useful.

Why Namespaces? Well… :) When a browser loads a document, it loads ALL the JavaScript into the browser. Objects that are not enclosed within a Namespace are Global, and Global Variables are Evil because they run the risk of interfering / overriding / clobbering previously defined objects (variables, functions, etc…). The JavaScript language, in its current form does not have native support for Namespacing . So, as pragmatic developers we realize the need to “Program Into [Our] Language, Not In It” - Steve McConnell, Code Complete 2nd Ed, Chapter 34.4. In the JavaScript language we use Objects to achieve Namespacing – we’ll cover this closer to the end of this post.

Don’t limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives … – Steve McConnell: Code Complete 2nd Ed, Chapter 34.4 

An example of when Namespaces could be used: Let’s say, we’re working on a team of 3 developers, each developer is working on a different widget / component for the same page. So inside our HTML / XHTML document we define and load three different JavaScript files and inside these files we have something like:
In someObscureWidgetJavaScriptFile1.js have:

  helloWorld = function(){ alert('hello world'); };

In someOtherObscureJavaScriptFile2.js we have:

  helloWorld = 'hello world';

In someOtherObscureJavaScriptFile3.js we have:

  helloWorld = { hello: 'hello', world: 'world' };

All these JavaScript files get loaded into the browsers global calling object (window), and each assignment of helloWorld interferes with the previous. When we attempt to reference helloWorld we’ll be depending on the order in which the JavaScript files were loaded – if the first file was loaded we’ll be able to display the alert, if the later file was loaded first we’ll be able to reference a string, and so on.

Back to the topic at hand, How do I create a Namespace in JavaScript.
Note: this approach to Namespacing was recommended and referenced in JavaScript: The Definitive Guide by David Flanagan, other methods of Namespacing can be found on the web (Namespacing your JavaScript by Dustin Diaze outlines an alternate approach). For me, the following seems more intuitive, and is recommended in Flanagan’s book – probably, the best JavaScript book written to date.

Ceating a Namespace in JavaScript:

// Create the namespace object. Error checking omitted here for brevity. 
 var myNameSpace;
 if (!myNameSpace) myNameSpace = {};
 myNameSpace.myPseudoClass = {}; 
 //JavaScript doesn't support classes,
 // so let's avoid confusing people and call this a Pseudo Class  

 // Don't stick anything into the namespace directly. 
 // Instead we define and invoke an anonymous function to create a closure 
 // that serves as our private namespace. This function will export its 
 // public symbols from the closure into the myNameSpace object 
 // Note that we use an unnamed function so we don't create any other 
 // global symbols.
 (function() { // Begin anonymous function definition  

   // Nested functions create symbols within the closure 
   function displayMyMessage() { alert(myMessage); }

   // Local variable are symbols within the closure. 
   // This one will remain private within the closure 
   var myMessage = 'Hello World';

   // This function can refer to the variable with a simple name 
   // instead of having to qualify it with a namespace 
   function getMyMessage() { return myMessage; }

   // Now that we've defined the properties we want in our private 
   // closure, we can export the public ones to the public namespace 
   // and leave the private ones hidden here. 
   var ns = myNameSpace.myPseudoClass;
    ns.displayMyMessage = displayMyMessage;
    ns.getMyMessage = getMyMessage;

 })(); // End anonymous function definition and invoke it

Then outside our namespace we can invoke our methods like this: myNameSpace.myPseudoClass.displayMyMessage();

Read Chapter 10, Modules and Namespaces in JavaScript: The Definitive Guide for a deeper dive into Namespaces and Modules in JavaScript!

If you’re still not convinced you need Namespaces and are interested in reading more about the issues surounding Global Data, then you may be interested in reading Chapter 13.3 (Global Data) in Code Complete.

Author: Adam Kahtava Categories: AJAX, JavaScript, Software Tags:
  1. January 29th, 2009 at 17:58 | #1

    Great article.

    Here is an article on how to use it with the jQuery object. In other words namespasing with the jQuery
    Namespace Your Javascript

  2. June 1st, 2009 at 20:56 | #2

    Hi, cool post. I have been wondering about this topic,so thanks for writing.

  1. No trackbacks yet.