Wednesday, July 22, 2009

JavaScript Namespaces

It's important to namespace your JavaScript code. I want one "master" namespace, and everything else under it (like YUI's namespacing approach). I fell into some potholes of browser compatibility on the way (with var foo; if (!foo) foo = {};), but here's what I ended up with:

// define master namespace
if (typeof foo === "undefined") var foo = {};

(function(){ // lexical scoping, allows "private" variables and functions

// define sub-namespace
if (!foo.bar) foo.bar = {};

// these don't leak outside
function helper() { /* ... */ } // "private" function
var counter = 0;                // "private" variable

// this function shows up globally under namespace foo.bar
foo.bar.func1 = function(x) { /* ... */ };

// not just functions
foo.bar.constant1 = 12;
foo.bar.shared_data = [];

})(); // end of lexical scoping

This way all the JS files can use the same namespace hierarchy, and can still be defined separately. No JS library necessary.

No comments:

Post a Comment