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.

Comments

  1. I highly recommend looking into Asynchronous Module Definitions (AMD) as a fully-developed JavaScript module build method: http://requirejs.org/docs/whyamd.html

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

    ReplyDelete
  3. That is actually the revealing module pattern.

    ReplyDelete

Post a Comment

Popular posts from this blog

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 f

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o