Skip to main content

Module Pattern in JavaScript

Couple of days back I wrote about the Constructor Pattern in JavaScript wherein I explained how classes can be simulated using functions in JavaScript. Also, on how the prototype property can be used to extend another class. The other important element in any of the Object-Oriented programming language is the concept of encapsulation i.e. providing private members that can be accessed only by the members of the same class. I came across the Module Pattern today and found that it is quite easy to achieve encapsulation in JavaScript. Though the variables in JavaScript can't be declared as private or public, but closures can be used to emulate encapsulation.

The var scoped variables defined inside a function are visible throughout the body of the function and will die once the function has completed its execution. This means that the var scoped variables can't be accessed outside the function and hence can be considered as 'private' variables of a class. This is exactly what we want from a JavaScript class, but there should be a way to access or update these members through a public interface. The member functions or variables can be made public by returning an object from that function. Here's is a simple module:

twitter = (function() { var twitterStatus = []; var currentIndex = 0; var getPreviousElement = function() { if(currentIndex != 0) return twitterStatus[--currentIndex]; else return twitterStatus[0]; } var getNextElement = function() { if(currentIndex != twitterStatus.length-1) return twitterStatus[++currentIndex]; else return twitterStatus[currentIndex]; } var pushMessage = function(message) { twitterStatus.push(message); } return { pushMessage: pushMessage, getPreviousElement: getPreviousElement, getNextElement: getNextElement } })();

There are quite a few things happening here. Firstly, I'm defining a self invoking function which is then assigned to a variable 'twitter'. When the function is invoked the various member variables and functions are defined and the function returns with an object containing references to these member functions. Now the variable 'twitter' can be used to invoke various functions (public methods). These functions are nothing but closures and will have read\write access to the private members (var scoped variables) of the function:

twitter.pushMessage("Message 1"); twitter.pushMessage("Message 2"); twitter.getPreviousElement(); twitter.getNextElement();

In this way it is more easier to organize the code in a particular namespace and not worry about other library functions present in the global namespace.


  1. I highly recommend looking into Asynchronous Module Definitions (AMD) as a fully-developed JavaScript module build method:

  2. I have started to look at various design patterns in JavaScript. I'll definitely look into AMD. Thanks for sharing it.

  3. That is actually the revealing module pattern.

  4. If you're a fan of the Module Pattern, take a look at the Definitive Module Pattern as well:


Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…