Namespacing Fundamentals

Namespaces can be found in almost any serious JavaScript application. Unless we’re working with a simple code snippet, it’s imperative that we do our best to ensure that we’re implementing namespacing correctly, as it’s not just simple to pick up, it’ll also avoid third-party code clobbering our own. The patterns we’ll be examining in this section are:

  1. Single global variables

  2. Prefix namespacing

  3. Object literal notation

  4. Nested namespacing

  5. Immediately-invoked Function

  6. Expressions

  7. Namespace injection

Single Global Variables

One popular pattern for namespacing in JavaScript is opting for a single global variable as our primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:

var myApplication =  (function () { 
        function(){
            //...
        },
        return{
            //...
        }
})();

Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as we have in the page.

Prefix Namespacing

One solution to the above problem, as mentioned by Peter Michaux, is to use prefix namespacing. It’s a simple concept at heart, but the idea is we select a unique prefix namespace we wish to use (in this example, myApplication_) and then define any methods, variables, or other objects after the prefix as follows:

var myApplication_propertyA = {};
var myApplication_propertyB = {};
function myApplication_myMethod(){ 
  //...
}

This is effective from the perspective of decreasing the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect.

This aside, the biggest issue with the pattern is that it can result in a large number of global objects once our application starts to grow. There is also quite a heavy reliance on our prefix not being used by any other developers in the global namespace, so be careful if opting to use this.

For more on Peter’s views about the single global variable pattern, read his excellent post on them: http://michaux.ca/articles/javascript-namespacing.

Object Literal Notation

Object literal notation, which we also cover in the Module pattern section, can be thought of as an object containing a collection of key-value pairs with a colon separating each pair of keys and values, where keys can also represent new namespaces.

var myApplication = {

    // As we've seen, we can easily define functionality for
    // this object literal..
    getInfo:function(){ 
      //...
    },

    // but we can also populate it to support 
    // further object namespaces containing anything
    // anything we wish:
    models : {},
    views : {
        pages : {}
    },
    collections : {}
};

One can also opt for adding properties directly to the namespace:

myApplication.foo = function(){
    return "bar";
}

myApplication.utils = {
    toString:function(){
        //...
    },
    export: function(){
        //...
    }
}

Object literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They are truly beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, object literals often also take into account tests for the existence of a variable by the same name, so the chances of collision occurring are significantly reduced.

The next sample demonstrates a number of different ways in which you can check to see if an object namespace already exists, defining it if it doesn’t.

// This doesn't check for existence of "myApplication" in
// the global namespace. Bad practice as we can easily
// clobber an existing variable/namespace with the same name
var myApplication = {};

// The following options *do* check for variable/namespace existence. 
// If already defined, we use that instance, otherwise we assign a new 
// object literal to myApplication.
// 
// Option 1: var myApplication = myApplication || {};
// Option 2  if( !MyApplication ){ MyApplication = {} };
// Option 3: window.myApplication || ( window.myApplication = {} );
// Option 4: var myApplication = $.fn.myApplication = function() {};
// Option 5: var myApplication = myApplication === undefined ? {} : myApplication;

You’ll often see developers opting for Option 1 or Option 2—they are both straightforward and are equivalent in terms of their end result.

Option 3 assumes that you’re working in the global namespace, but it can also be written as:

myApplication || (myApplication = {});

This variation assumes that myApplication has already been initialized, so it’s only really useful for a parameter/argument scenario, as in the following example:

function foo() {
  myApplication || ( myApplication = {} );
}

// myApplication hasn't been initialized, 
// so foo() throws a ReferenceError

foo(); 

// However accepting myApplication as an
// argument

function foo( myApplication ) {
  myApplication || ( myApplication = {} );
}

foo();

// Even if myApplication === undefined, there is no error
// and myApplication gets set to {} correctly 

Options 4 can be useful for writing jQuery plug-ins where:

// If we were to define a new plug-in..
var myPlugin = $.fn.myPlugin = function() { ... };

// Then later rather than having to type:
$.fn.myPlugin.defaults = {};

// We can do:
myPlugin.defaults = {};

This results in better compression (minification) and can save on scope lookups.

Option 5 is a little similar to Option 4, but is a long form that evaluates whether myApplication is undefined inline—such that it’s defined as an object if not—and set to an existing value for myApplication if so.

It is shown just for the sake of being thorough, but in most situations, Options 1–4 will more than suffice for most needs.

There is, of course, a great deal of variance in how and where object literals are used for organizing and structuring code. For smaller applications wishing to expose a nested API for a particular self-enclosed module, you may just find yourself using the Revealing Module pattern, which we covered earlier in the book:

var namespace = (function () {

    // defined within the local scope
    var privateMethod1 = function () { /* ... */ },
        privateMethod2 = function () { /* ... */ }
        privateProperty1 = "foobar";

    return {

        // the object literal returned here can have as many 
        // nested depths as we wish, however as mentioned, 
        // this way of doing things works best for smaller, 
        // limited-scope applications in my personal opinion
        publicMethod1: privateMethod1,

        // nested namespace with public properties
        properties:{
            publicProperty1: privateProperty1
        },

        // another tested namespace
        utils:{
            publicMethod2: privateMethod2
        }
        ...
    }
})();

The benefit of using object literals here is that they offer us a very elegant key/value syntax to work with; one where we’re able to easily encapsulate any distinct logic or functionality for our application in a way that clearly separates it from others and provides a solid foundation for extending our code.

var myConfig = {

    language: "english",

    defaults: {
        enableGeolocation: true,
        enableSharing: false,
        maxPhotos: 20
    },

    theme: {
        skin: "a",
        toolbars: {
            index: "ui-navigation-toolbar",
            pages: "ui-custom-toolbar"    
        }
    }

}

Note that JSON is a subset of object literal notation, and there are really only minor syntactical differences between it and the above (e.g., JSON keys must be strings). If, for any reason, one wishes to use JSON for storing configuration data instead (e.g., for simpler storage when sending to the backend), feel free to. For more on the object literal pattern, I recommend reading Rebecca Murphey’s excellent article on the topic, as she covers a few areas we didn’t touch upon.

Nested Namespacing

An extension of the object literal pattern is nested namespacing. It’s another common pattern used that offers a lower risk of collision due to the fact that even if a namespace already exists, it’s unlikely the same nested children do.

Does this look familiar?

YAHOO.util.Dom.getElementsByClassName("test");

Older versions of Yahoo!’s YUI library use the nested object namespacing pattern regularly. During my time as an engineer at AOL, we also used this pattern in many of our larger applications. A sample implementation of nested namespacing may look like this:

var myApp =  myApp || {};
 
// perform a similar existence check when defining nested 
// children
myApp.routers = myApp.routers || {};
myApp.model = myApp.model || {};
myApp.model.special = myApp.model.special || {};

// nested namespaces can be as complex as required:
// myApp.utilities.charting.html5.plotGraph(/*..*/);
// myApp.modules.financePlanner.getSummary();
// myApp.services.social.facebook.realtimeStream.getLatest();

Note

The above differs from how YUI3 approaches namespacing as modules there use a sandboxed API host object with far less and far shallower namespacing.

We can also opt to declare new nested namespaces/properties as indexed properties as follows:

myApp["routers"] = myApp["routers"] || {}; 
myApp["models"] = myApp["models"] || {}; 
myApp["controllers"] = myApp["controllers"] || {};

Both options are readable, organized, and offer a relatively safe way of namespacing our application in a similar fashion to what we may be used to in other languages. The only real caveat, however, is that it requires our browser’s JavaScript engine first locating the myApp object and then digging down until it gets to the function we actually wish to use.

This can mean an increased amount of work to perform lookups; however, developers such as Juriy Zaytsev have previously tested and found the performance differences between single object namespacing versus the “nested” approach to be quite negligible.

Immediately Invoked Function Expressions (IIFE)s

Earlier in the book, we briefly covered the concept of an immediately invoked function expression; IIFE, which is effectively an unnamed function, immediately invoked after it’s been defined. If it sounds familiar it’s because you may have previous come across it referred to as a self-executing (or self-invoked) anonymous function, however I personally feel Ben Alman’s IIFE naming is more accurate. In JavaScript, because both variables and functions explicitly defined within such a context may only be accessed inside of it, function invocation provides an easy means to achieving privacy.

IIFEs are a popular approach to encapsulating application logic to protect it from the global namespace but also have their use in the world of namespacing.

Examples of IIFEs can be found below:

// an (anonymous) immediately-invoked function expression
(function () { /*...*/})();

// a named immediately-invoked function expression
(function foobar () { /*..*/}());

// this is technically a self-executing function which is quite different
function foobar () { foobar(); }

while a slightly more expanded version of the first example might look like:

var namespace = namespace || {};

// here a namespace object is passed as a function 
// parameter, where we assign public methods and 
// properties to it
(function( o ){    
    o.foo = "foo";
    o.bar = function(){
        return "bar";    
    };
})( namespace );

console.log( namespace );

Whilst readable, this example could be significantly expanded on to address common development concerns such as defined levels of privacy (public/private functions and variables) as well as convenient namespace extension. Let’s go through some more code:

// namespace (our namespace name) and undefined are passed here 
// to ensure 1. namespace can be modified locally and isn't 
// overwritten outside of our function context
// 2. the value of undefined is guaranteed as being truly 
// undefined. This is to avoid issues with undefined being 
// mutable pre-ES5.

;(function ( namespace, undefined ) {

    // private properties
    var foo = "foo", 
        bar = "bar";

    // public methods and properties
    namespace.foobar = "foobar";
    namespace.sayHello = function () {
        speak( "hello world" );
    };

    // private method
    function speak(msg) {
        console.log( "You said: " + msg );
    };

    // check to evaluate whether "namespace" exists in the 
    // global namespace - if not, assign window.namespace an 
    // object literal

}( window.namespace = window.namespace || {} ));


// we can then test our properties and methods as follows

// public

// Outputs: foobar
console.log( namespace.foobar );

// Outputs: hello world
namescpace.sayHello();

// assigning new properties
namespace.foobar2 = "foobar";

// Outputs: foobar
console.log( namespace.foobar2 );

Extensibility is of course key to any scalable namespacing pattern and IIFEs can be used to achieve this quite easily. In the below example, our “namespace” is once again passed as an argument to our anonymous function and is then extended (or decorated) with further functionality:

// let's extend the namespace with new functionality
(function( namespace, undefined ){

    // public method
    namespace.sayGoodbye = function () {
        console.log( namespace.foo );
        console.log( namespace.bar );
        speak( "goodbye" );
    }    
}( window.namespace = window.namespace || {});

// Outputs: goodbye
namespace.sayGoodbye();

If you would like to find out more about this pattern, I recommend reading Ben’s IIFE post for more information.

Namespace Injection

Namespace injection is another variation on the IIFE in which we “inject” the methods and properties for a specific namespace from within a function wrapper using this as a namespace proxy. The benefit this pattern offers is easy application of functional behavior to multiple objects or namespaces and can come in useful when applying a set of base methods to be built on later (e.g., getters and setters).

The disadvantages of this pattern are that there may be easier or more optimal approaches to achieving this goal (e.g., deep object extension or merging), which I cover earlier in the section.

Below we can see an example of this pattern in action, where we use it to populate the behavior for two namespaces: one initially defined (utils) and another which we dynamically create as a part of the functionality assignment for utils (a new namespace called tools).

var myApp = myApp || {};
myApp.utils =  {};

(function () {
  var val = 5;

  this.getValue = function () {
      return val;
  };
   
  this.setValue = function( newVal ) {
      val = newVal;
  }
      
  // also introduce a new sub-namespace
  this.tools = {};
    
}).apply( myApp.utils );  

// inject new behaviour into the tools namespace
// which we defined via the utilities module

(function () {
    this.diagnose = function(){
        return "diagnosis";   
    }
}).apply( myApp.utils.tools );

// note, this same approach to extension could be applied
// to a regular IIFE, by just passing in the context as 
// an argument and modifying the context rather than just
// "this"

// Usage:

// Outputs our populated namespace
console.log( myApp );

// Outputs: 5
console.log( myApp.utils.getValue() );

// Sets the value of `val` and returns it
myApp.utils.setValue( 25 ); 
console.log( myApp.utils.getValue() );

// Testing another level down
console.log( myApp.utils.tools.diagnose() );

Angus Croll has also suggested the idea of using the call API to provide a natural separation between contexts and arguments previously. This pattern can feel a lot more like a module creator, but as modules still offer an encapsulation solution, we’ll briefly cover it for the sake of thoroughness:

// define a namespace we can use later
var ns = ns || {}, 
    ns2 = ns2 || {};

// the module/namespace creator
var creator = function( val ){

    var val = val || 0;

    this.next = function () {
        return val++
    };

    this.reset = function () {
        val = 0;
    }
}

creator.call( ns );

// ns.next, ns.reset now exist
creator.call( ns2 , 5000 );

// ns2 contains the same methods
// but has an overridden value for val
// of 5000

As mentioned, this type of pattern is useful for assigning a similar base set of functionality to multiple modules or namespaces. I would however only really suggest using it where explicitly declaring functionality within an object/closure for direct access doesn’t make sense.

Get Learning JavaScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.