A lot of JavaScript programmers use an anonymous function at the top level, to establish a scope. This allows variables to be defined in a file (or module if your prefer), without adding anything to the global namespace.

The problem with this, however, it that it becomes awkward when you do need to add something to the global namespace.

Here’s a trick that solves this problem.

    (function()
    {
        var global = (function(){return this;}).call();
        global.Formula = function (){
            // body of function
        };
    })();

This code is equivalent to:

    var Formula;
    (function()
    {
        Formula = function (){
            // body of function
        };
    })();

Both forms have the same number of lines of code, but the first pulls ahead for each additional object added to the global namespace.  But there are other advantages.

  • It is made explicit, that the assignment to Formula is being made in the global namespace.
  • Suppose you decide that Formula and its companions should live in a different namespace.  In the first, simply search and replace on ‘global’ and replace the definition of global.
  • In the first, we take care to explicitly obtain the object we are changing, namely the global object.
  • According to Douglas Crockford, “JavaScript’s global object [...] is far and away the worst part of JavaScript’s many bad parts”. Writing as in the first example discourages and makes explicit the use of the global object.
About these ads