What isn’t in a name?

June 16th, 2009 § Comments Off on What isn’t in a name? § permalink

If you don’t already know, polluting the global variable pool is a bad, evil thing in JavaScript land. If you’re not concerned with overwriting existing code then at least think about protecting your code from being overwritten by keeping it in your own namespace. All you need to create a namespace in JavaScript is an object literal.

Say you’re tasked with incorporating a third-party widget into your home page. You drop in their include but suddenly one of the scripts on your site breaks. You haven’t changed your code so you assume it’s the include causing trouble. However, a JSLint shows that their syntax checks out fine. Looking through your functions you narrow the misbehaving lines down to the following:

function findElement(el) {
    return document.getElementById(el);
}

function updateNews(content) {
    findElement('news').innerHTML=content;
}

That is some horrible code. Worse, that’s horrible code in the global pool. Cracking open the third-party include you see this:

updateNews = function(container,source,freq)
{
    // Snip....
}

My, that function name looks awfully familiar. In fact, it’s the same as yours. That means your code and the third-party code are fighting in the global variable pool. What’s a clever programmer to do? Do what works in other languages, of course!

Time to carve out your own namespace

This is ridiculously easy if you understand what object literals are and how to self-invoke an anonymous function. Those terms both sound scarier than they are. You simply create an object literal to act as your namespace &#8211 which is a bucket for all your code – then use anonymous functions to assign functions into it. Keeping with the theme of being a polite player in the global pool also make sure your namespace is either brand new or extends any existing namespace.

var AY = AY || {}; //Don't overwrite existing namespaces
AY.News = function() //A 'News' bucket for all news-related tasks
{
    //The 'var' forces the findElement method 
    //into the News scope, not global
    var findElement = function(el)
    {
        return document.getElementById(el);
    }
    
    //Anything in the return becomes publicly accessible, yet 
    //is also able to access private methods and variables
    return {
        updateNews: function(content)
        {
            findElement('news').innerHTML = content;
        }
    }
}(); //Self-invoke to make this available immediately
AY.News.updateNews('Hai');

What’s happening here? Well instead of dropping all of your code into the global you can stash it in a single namespace. In my case I’ve named my namespace as AY, after my name. I used all capital letters to signify that this is not a variable or method belonging to any other code. For news-related items I’ve created a News bucket.

Inside of my News bucket there are a few things happening. I’ve decided that findElement should be a private method in my namespace so by prepending it with the var = I designate it as existing only inside the AY.News namespace. Without a public accessor no outside code can run that method. My return passes an object literal which houses any public methods, in this case the updateNews method. Because they are a part of my AY.News namespace these public methods can access private methods, which is why the updateNews code still works.

Finally, the closing parentheses cause the anonymous function to automatically run, or self-invoke. This action executes the function and, during its execution, hits the return which is what causes the return data to be assigned to AY.News. The return is an object literal itself that contains a reference to the “private” updateNews, which will execute the update.

That’s it! There’s no more to it. I’ll grant that for personal scripts this technique is not absolutely necessary but if you ever want your code to play nicely in another environment it’s a good practice and makes other programmers less hesitant to use your code. Comments regarding execution of this technique are more than welcome. This is my personal flavor and because of JavaScript’s flexibility I’m sure there are some other great techniques out there. Comment away!

Recommended reading:

2009-06-17: Reordered and cleaned up copy.