JS Tidbits: Namespace / Anonymous Function

1 comment | Posted: 8 December 06 in Tutorials, by Cody Lindley

Emulating namespaces in JavaScript, in order to avoid scoping collisions (identifiers with the same name in the same scope), is typically done by creating an object object and storing code in the scope of the new object, rather than in the global window scope of the browser. This topic has been discussed many times by many developers. Typically, code to create a namespace will look something like this:

var namespace = {}; //create object object using literal
namespace.myProperty = "string"; //add a property
namespace.myMethod = function(){ /*add code to be parsed by namespace.myMethod()*/ }; //add a method

or this,

var namespace = function() {
    return {// create an object object
        myProperty : "string", //add a property
        myMethod : function(){ /*add code to be parsed by namespace.myMethod()*/  } //add a method
    }
}();

Now this is all well and good - and creating an object object to store code has its usages - but a namespace is not always needed. That is, sometimes we just want to run/initialize code, and having to wait for the document to completely load is not an issue. In such a scenario, an anonymous function that invokes itself immediately might do. It will serve to provide a secure scope in which we can write our script.

(function() { // create an anonymous function
    var myProperty = "string"; //create variable
    function myMethod(){/*add code to be parsed by myMethod()*/ }; // create function
    alert(myProperty); //access variable without using object notation
})();

Using an anonymous function removes any possibilities of scope conflicts because the function is not given an identifiable name. Since it's not given a name, there will be no symbol added to the global window scope of the browser. The implication, then, is that there are no possibilities of like-named functions, variables, or objects conflicting with each other. This method fails, however, if the code inside of the function is dependent upon elements in the DOM appearing after it in the document flow. The only way to fix this is to make sure the anonymous function (in its entirety) is the last child element of the body element. This will ensure that the browser has loaded non-dynamic elements before it tries to run the JavaScript code.

If moving scripts into the body element is not a viable solution (you prefer them staying in the (x)html head element), then you can name the anonymous function and call it when the body element has been completely loaded into the browser, as follows:

var goOnDocLoad = function() { // create an anonymous function
    var myProperty = "string"; //create variable
    function myMethod(){/*add code to be parsed by myMethod()*/ }; // create function
    alert(myProperty); //access variable without using object notation
}
window.onload = goOnDocLoad;

This is still a good solution for those trying to avoid creating an object object solely to create a single namespace. With this method, it's important to name the function uniquely as to avoid conflicts with names used by other JavaScript developers.

Now don't let it be said that I have anything against the object object. If you prefer to write code in the context of JavaScript's objects, then proceed with the techniques mentioned at the beginning of this article. The main point I am trying to make is that you always have options. Being trendy might not always be practical. In this case, writing code in the context of object objects, while popular, is not always necessary if you're only after a single namespace.

Discuss This Topic

  1. 1 Dustin Diaz

    The whole point of a namespace is to avoid your Public interface collisions. If you’re writing something that doesn’t involve developers sharing code and having a uniform API... or an actual implementation of an API – an anonymous block is the way to go. It allows you to be messy and play nice with the other JavaScript kids at the same time :)

     

Comments closed after 2 weeks.