Javascript Revealing Module Pattern2 min read

I’m a big fan of Javascript’s Module Pattern as it keeps things simple and on the other hand easy to read and use. Program design gets less complicated and scoping a breeze, that’s why this pattern is a must in application architecture!
So i will show you in an easy way how to use it.

Creating a module is easy in Javascript.

Firstly, we must use IIFE or Immediately-Invoked-Function-Expression which basically creates new scope with a wrapper around function logic.

 
 (function() {     
// code
}());

Secondly, we need to create namespace to our IIFE so we can access methods inside of our IIFE.

 
 var Library = (function() { 
// code
}());

This way we created module with namespace “Library” which can now use private methods, although, in Javascript there are no strictly private methods.

 
 var Library = (function() { 
"use strict";
var privateMethod = function() { // code }
}());

The “return” of the Mack

In example as above, privateMethod, if called outside of our IIFE will break program but will be availble to use inside of our IIFE.
To make our privateMethod available publicly we must introduce the “return” keyword.

var Library = (function () {
"use strict";
var privateMethod = function() {
// code
}
return {
publicMethod: privateMehod
};
}());

This is how we managed to return an Object , which in this case is our Library, with a function which is publicly available via our Library namespace.

So, to use it we just need to call

Library.publicMethod();

Extending Modules

To make things more readable we will introduce local scope object to our Library.
This way will be easier to read which methods are public and which are private. Also, this is how we may extend other modules easier.
To accomplish this we will do the following:

var Library = (function (library)  {
"use strict";
// locally scoped object
var _ = {};
.privateMethod = function () { // code }; // public method library.publicMethod = .privateMethod;
return library;
}( Library || {} ));

To extend other modules:

var Library2 = (function (library) {
"use strict";
// locally scoped object
var _ = {};
_.privateMethod = function () {
// code
};
// public method
library.newPublicMethod = _.privateMethod;
return library;
}( Library || {} ));

Leave a Reply

Your email address will not be published. Required fields are marked *