Introduction to the JavaScript Module Design Pattern | Unleashed Technologies
Loading...

Blog Header ImageIn a previous blog post, I gave a quick overview of how closures work in JavaScript. Closures are a very powerful tool in JS development and can be used in many different design patterns. In this post, we'll look at how the module pattern works thanks to these closures.

The module pattern is a popular design pattern used to emulate the basics of classes in object-oriented languages. We can wrap a mixture of public and private methods/variables inside a single object, shielding certain pieces from the global scope. This reduces the chance that your function names will conflict with other functions from other scripts. We can have certain methods and variables that are only accessible from within the module, ensuring that nothing can tamper with or access this hidden information. Let's take a look at an example:

var myModule = (function(
	var hits = 0;
	return {
		increment: function() {
			return hits++;
		},
		reset: function() {
			hits = 0
		}
	};
))();

This module is completely self-contained in the global object called 'myModule'. Other parts of the code cannot directly read the value of hits or call 'increment()' or 'reset()'. In fact, the 'hits' variable is completely shielded from the global scope so it acts like a private variable. It only exists inside that module's closure, so the only code with access to its scope are the two module functions.

Inside the module pattern we 'return' a JavaScript object. This object gets assigned to 'myModule', so you can interact with any member of that object like this:

myModule.increment();
myModule.increment();
myModule.increment();
myModule.reset();

The methods are essentially 'namespaced' inside of 'myModule' so you must prefix them with 'myModule.' when calling them. Here's a general framework you can use for this pattern:

var myNamespaceName = (function(){
	
	var myPrivateVariable = 0;
	
	var myPrivateMethod = function(text){
		alert(text);
	}
	
	return {
	
		myPublicVariable: "foo",
		
		myPublicFunction: function(bar){
			myPrivateVariable++;
			myPrivateMethod(bar);
		}
	
	}
	
})();

If you plan on doing alot of work with JavaScript, I'd strongly recommend using this design pattern in your projects. For a more-detailed guide to the module pattern, check out this fantastic resource: JavaScript Module Pattern In Depth. If you'd like to see a more-advanced example of the module pattern, check out our "maxchars" plugin for jQuery.