How will you make it if you never even try?

February 11, 2011

An improvement to the Javascript Module pattern

Filed under: C# — charlieflowers @ 2:59 pm

Wow, a nice idea just hit me while I was in the shower. It is an improvement to the Javascript Module pattern. (It’s not earthshaking, but it offers a nice additional bit of protection).

The general idea of the module pattern is that you take some script that would otherwise execute in global scope and wrap it in a function, which you then execute immediately, like this:

(function(GLOBAL) {
    var x = 42;
    // more code here
}(window));

Note that right after the function has been declared, we have followed it with (), which causes it to execute. This gives you a scope within which you can put your code. You can return objects out of here that contain closures, and hence create effects such as private internal state.

It’s fantastic, and though it can be overused (like any good thing), it should be used a lot. You’ll see it used often in the source code of jQuery, JavascriptMVC, and many other well-factored JavaScript code bases.

The Improvement: Use call() to control the “this” pointer

So here’s the improvement. We’re going to take control of the “this” pointer inside our module (aka, the “context”), and make sure that it is not the global scope. We can still pass the global scope in to our module, so that we can have global effects if we want to. But this way, all our global effects will be made obvious. Plus, there are some common mistakes such as this one that can accidentally pollute the scope pointed to by your “this” pointer. By making sure our “this” pointer is not the global scope, we prevent those mistakes from accidentally vomiting directly into the global scope.

Here’s what we do:

(function(GLOBAL) {
    var x = 42;
    // more code here
}.call({}, window);

Notice we have called the module function using “call()“, which allows us to specify the “this” pointer. And we’ve passed an empty object for the “this” pointer.

Often times when you’re doing heavy JavaScript development, your particular implementation of the Module pattern is boilerplate that you roll into a snippet that automatically gets inserted whenever you create a new file. Incorporating this improvement just introduces yet one more level of protection from some of the kinds of mistakes you’re trying to watch out for.

Blog at WordPress.com.