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.

Comments

I can only recommend that you pick up a copy of Modern DOM Scripting from SitePoint when it gets published...:-)

Posted by sil (#)

Yep, Javascript as a language is nice. It even has not just function pointers, but actual closures. It's much more expressive than your typical ALGOL-derived species and much better than PHP as far as dynamic languages are concerned, since the language core is well designed and organized. And assuming good DOM support, DHTML works as well as it should.

DOM is not the most effortless API though, and I have gripes with how the DOM implementation in Javascript makes things unnecessarily painful if you try to write in a more functional style. It's also overly hard to debug Javascript running in a browser.

It's no Perl, but all in all, I like Javascript — plainly evident by the fact that I enjoy writing code in it despite all the gripes I have.

Posted by Aristotle (#)