November 17, 2004

Namespaces in Javascript

Naming clashes have always been one of my main concerns when writing Javascript. It is no longer. Stuart Langridge (of sorttable fame) has come up with an elegant solution that uses hashmaps to emulate something like namespace functionality in Javascript:

var Util = {

    foo: function() {
        alert("This is foo!");
    },

    bar: function() {
        alert("This is bar!");
    }

}

// In a nearby piece of code...

Util.foo();
Util.bar();

Having done a lot of Javascript lately, believe me when I tell you to forget everything you think you know about it from 1998. These days Javascript has lots of goodness to offer, including but not limited to function pointers, event handlers and native regular expressions. Manipulating an HTML document through the DOM works like a charm, and actually operates flawlessly and rock solid throughout all browsers.

Update: I haven't actually tried it out, but apparently it is also possible to emulate namespaces by creating a new Object() for each namespace you need and adding your functions as methods to these objects. And again I'm stunned how all of this has been dangling in front of my nose for ages.