The Module Pattern

The great thing about JavaScript is you can make up your own structure. The awful thing about JavaScript is everyone makes up their own structure. (kidding).

One my my favorite design patterns for keeping things organized is what’s called the “Module Pattern”. I’m a fan of keeping things as simple as possible, and the Module Pattern let’s you write very clean, decoupled code, without over complicating things.

Creating a Module

Creating a Module begins with an IIFE or an immediately-invoked functional expression. It’s basically a function wrapped in an extra paren which lets the function execute itself. This is known as a function expression. Everything that happens inside of it are kept private from the parent scope. I’ll explain why thats awesome in a minute.

// an IIFE
(function(){
	// code
})()

To declare it as a module, simply give it a name space like this:

// a module function
var awesomeModule = (function(){
	// code
})()

Privacy

One of the fantastic things about the Module pattern is how easy it is to implement privacy in you object. Privacy basically means that what happens in your object, stays in your object, unless told otherwise.

var awesomeModule = (function(){
	var thisVar = "foo";
	function _privateMethod (){
		// code
	}
	return {
		var publicMethod = function(){
			return thisVar;
		}
	}
})()


alert(thisVar) // undefined
alert (awesomeModule.pubicMethod()) // foo

In the example above thisVar is not exposed outside of awesomeModule until the publicMethod() is ran. It’s encapsulated within the object, making it a Private variable.

Historically Javascript has not been given the same respect as some other languages associated with object-oriented programming. But when used properly, such as taking advantage of encapsulation, Javascript can be just as powerful as it’s peers.

The Module Pattern in Practice

I use the Module Pattern whenever I have data I don’t want to directly expose (such as values within a game). Traditionally encapsulation is synonymous with security but on client side Javascript everything you have to be careful what you calculate on the browser. In a more secure environment (like on a server), the security …

Read More»