Better JavaScript–Namespaces

I have recently had the opportunity to do some JavaScript-heavy programming which has allowed me take stock of my understanding of the different structures in this language.  Today I’m going to look at one of the most straightforward challenges in JavaScript – declaring namespaces.

JavaScript doesn’t really have the concept of namespacing – so while there are a few ways of doing namespaces, they’re all actually hacks.  If you look at the relevant question on StackOverflow you’ll see that there are quite a few opinions on the best way of doing namespaces.

The method I’m advocating is based on an article on the Enterprise jQuery site.  The whole approach is pretty bulletproof (someone else can’t go and re-declare undefined or $ and break your whole library).  It allows you to declare private and public functions and extend your namespace later on – this ticks all the right boxes on my checklist.

Let’s have a look at an example.

(function( coffeeMachine, $, undefined ) {
    //Private Property
    var coffeeGood = true;

    //Public Property
    coffeeMachine.bean = "Yirgacheffe";

    //Public Method
    coffeeMachine.brew = function() {
        clean();
        console.log( "Freshly brewed " + coffeeMachine.bean + " ready and waiting");
    }

    //Private Method
    function clean() {
        console.log( "Cleaning the coffee machine" );
    }    
}( window.coffeeMachine = window.coffeeMachine || {}, jQuery ));

This is very similar to the example in the link above – I would really recommend reading through it – it’s a much better explanation than I could come up with.

The entire function is structured as a self-executing anonymous function.  The parameters are particularly clever – for example, undefined is declared as a parameter but not actually used.  This actually makes sense since in JavaScript we can actually redefine undefined – so if you’re using some strange 3rd party library which does that this function will still work as expected.

What I really like about this way of using namespaces is how easy it is to extend the namespace – you use exactly the same syntax.

//Adding New Functionality to the Coffee Machine
(function( coffeeMachine, $, undefined ) {
    coffeeMachine.roast = function() {
      console.log( "Roasting some toasty " + coffeeMachine.bean );           
  }
}( window.coffeeMachine = window.coffeeMachine || {}, jQuery ));

In the code block where we are adding functionality we have access to all public methods and properties, but not to private members – which is pretty much what you would expect.

The only area where this syntax is not applicable is if you want to declare actual JavaScript objects – for example, if we wanted to create a specific instance of a coffee machine.  I will take a look at how to do that in a future post.

Happy coding.

Tags: JavaScript

  1. Eli Perelman says:

    The correct term for what you are describing is "immediately invoked function expression", because the function is not self-executing:

    http://benalman.com/news/2010/11/immediately-invoked-function-expression/

  2. Jaco Pretorius says:

    Thanks, you're right. I was actually reading that last night.

  3. Alex says:

    You can also use namespace like this:

    $.namespace("com.mysite", {
    //…
    });

    The implementation of $.namespace can be found here: https://github.com/alexo/Javascript-Utilities/blob/master/jQueryPlugins/namespace/jquery.namespace.js