Understanding Js : Module pattern

The Module Pattern is one of the most common design patterns used in JavaScript. It is easy to use and creates encapsulation of our code.This allows faster namespace resolution, avoid collision of the methods/variables with other global APIs and provides cleaner code. There are many different variations of the module pattern, lets look into few of these.

Basic Module Pattern


var myModule = (function() {

var privateVariable = 'privateVariable';

function privateMethod() {
console.log("Private function");
}

return {
publicMethod: function() {
console.log("Public function");
}
};
}());

myModule.publicMethod();
console.log(myModule.privateVariable);
myModule.privateMethod();

So we have a Immediately Invoked Function Expression or IIFE assigned to a variable. As we know from our scope discussions in previous post that variables and functions inside a IIFE are bound to that IIFE scope only.  So privateVariable, privateMethod could only be accessed within that IIFE. At the end we returned an object having a function. Lets see the result

modulePattern1

As you can see only the method returned is accessible, everything else is hidden. The Module Pattern must satisfy the following:

  • Private members live in the closure.
  • Public members are exposed in the return object.

Revealing Module Pattern

The Revealing Module Pattern is the most famous and most popular of the Module Pattern variants. Using the return statement we can return a object literal that ‘reveals’ only the methods or properties we want to be publicly available.


var myModule = (function() {

var privateVariable = 'privateVariable';

function privateMethod() {
console.log("Private function");
}

function publicMethod() {
console.log("Public function");
}

return {
globalMethod:publicMethod
};
}());

myModule.globalMethod();
myModule.publicMethod();

modulePattern2

The benefit to the Revealing Module Pattern is that we can look at the bottom of our modules and quickly see what is publicly available for use.

You can also pass in parameters to your IFFE’s like window, jQuery at the end in order to use it inside.


var myModule = (function(window,$) {

var privateVariable = 'privateVariable';

function privateMethod() {
console.log("Private function");
}

function publicMethod() {
console.log("Public function");
}

return {
globalMethod:publicMethod
};
}(window,jQuery));

There are many other variants to module pattern like Module Pattern with Return Object Stub, where we basically define an empty return object stub at the beginning and all the public member are defined as a member of that stub and at the end of your IFFE you return this stub.

ES6 introduces a standardized module format. 

Advertisements
%d bloggers like this: