Explicit use of JavaScript’s global object Friday, Jul 17 2009 

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.

Is JavaScript’s new syntactic sugar? Sunday, Jul 12 2009 

JavaScript has a ‘new’ operator for creating objects. Each object in JavaScript has a hidden pointer to a prototype object, from which it inherits properties. This pointer is set when the object is created, and cannot be changed during the lifetime of the object.

When ‘new’ is used, an object is created that has other than the usual default Object prototype object.

From ‘new’ we can define a function create(proto) that returns an object whose prototype object is ‘proto’. (I first saw this in Douglas Cockcroft’s book JavaScript: The Good Parts, but he calls it ‘beget’.)

Conversely, from ‘create’ we can define a function, say ‘New’ that has the same functionality as the ‘new’ operator. (In JavaScript ‘new’ is a keyword, whose meaning can be changed.)

The ‘create’ operator is in some sense simpler than the ‘new’ operator, but each can be defined in terms of the other. According to Wikipedia, syntactic sugar “is syntax designed to make things easier to read or to express, while alternative ways of expressing them exist”.

I think ‘create’ is simpler to use and understand than ‘new’, and so I don’t regard it as syntactic sugar for the creation creation of objects.  The same Wikipedia term also suggests the term  syntactic saccharin for gratuitous syntax which does not actually make programming easier.  I consider ‘new’ to be syntactic saccharin.