Please join me at my new location

Thursday, April 10, 2008

Two Functions Enter. One Function Leaves.

What happens when two applications declare a function with the same name in the same namespace? A huge headache.

A big problem with Javascript as it is today is that there is no insulation between your application and someone else's. When two functions are declared with the same name in the same scope, the last declaration "wins". Given this sad state of affairs, how can you work around this problem?

Code Defensively.

There's simple pattern for insulating your application. It involves two things I've talked about before: closures and anonymous functions. Consider the following code:

(function(scope) {

   function doStuff() {

   function doSomethingElse() {

   scope.doStuff = doStuff;


When run, the above code will expose doStuff by adding it to the passed object. If that code is run in the global scope then this refers to the global object. Everything that doesn't need to be exposed stays neatly hidden inside the closure. Congratulations, you've just reduced the surface area of your application to the bare minimum you'll be less susceptible to someone else's application trampling all over yours.

Combining this pattern with the unobtrusive Javascript methodology will effectively reduce your application's surface area to 0. Short of another application overwriting event handlers and data on shared DOM elements you've insulated yourself. What's even better is that if you don't need to expose anything a build script can bundle your sources files into one file wrapped it in an anonymous function and obfuscate it without you having to think.