Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

4.1. Module Pattern

The module pattern is a great way to encapsulate logic and prevent global namespace pollution. It’s all made possible by anonymous functions, which are arguably the single best feature of JavaScript. We’ll just create an anonymous function and execute it immediately. All the code residing within the function runs inside a closure, providing a local and private environment for our application’s variables:

(function(){
  /* ... */
})();

We have to surround the anonymous function with braces () before we can execute it. JavaScript requires this so it can interpret the statement correctly.

4.1.1. Global Import

Variable definitions inside the module are local, so they can’t be accessed outside in the global namespace. However, the application’s global variables are all still available, and they can be readily accessed and manipulated inside the module. It’s often not obvious which global variables are being used by a module, especially when your modules get larger.

In addition, implied globals are slower to resolve because the JavaScript interpreter has to walk up the scope chain to resolve them. Local variable access will always be faster and more efficient.

Luckily, our modules provide an easy way to resolve these problems. By passing globals as parameters to our anonymous function, we can import them into our code, which is both clearer and faster than implied globals:

(function($){
  /* ... */
})(jQuery);

In the example above, we’re importing the global variable jQuery into our module and aliasing it to $. It’s obvious which global variables are being accessed inside the module, and their lookup is quicker. In fact, this is the recommended practice whenever you want to use jQuery’s $ shortcut, which ensures that your code won’t conflict with any other libraries.

4.1.2. Global Export

We can use a similar technique when it comes to exporting global variables. Ideally, you should be using as few global variables as possible, but there’s always the odd occasion when they’re needed. We can import the page’s window into our module, setting properties on it directly, thereby exposing variables globally:

(function($, exports){

  exports.Foo = "wem";

})(jQuery, window);

assertEqual( Foo, "wem" );

The fact that we’re using a variable called exports to set any global variables means the code is clearer, making it obvious which global variables a module is creating.