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 aspects of this pattern are extremely useful.

I find it’s key benefit is organization. You don’t have to declare a bunch of this keywords throughout your methods as you would in other design patterns. Objects are extremely portable and it gives the flexibility to reactor without having to rewrite a bunch of stuff.

Whos gonna win?

var raffle = (function() {
    var _privateMethod = function(myName) {
        if (myName === "Matt") alert("You win! Keep up the good work!")
        else alert("Sorry mate, try again")
    }
    return {
        publicMethod: function(myName) {
            _privateMethod(myName)
        }
    }
})()
raffle.publicMethod("Matt")

There is a slightly more in depth article by Ben Cherry here.

If you would like to dig in to more design patterns, there is a great book by Addy Osmani

Category: Product #: Regular price:$ (Sale ends ) Available from: Condition: Good ! Order now!
Reviewed by on. Rating:

Comments

comments