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.
[syntax_prettify] (function() {
// code
}()); [/syntax_prettify]
Secondly, we need to create namespace to our IIFE so we can access methods inside of our IIFE.
[syntax_prettify] var Library = (function() {
// code
}()); [/syntax_prettify]
This way we created module with namespace “Library” which can now use private methods, although, in Javascript there are no strictly private methods.
[syntax_prettify linenums="linenums" ] var Library = (function() {
"use strict";
var privateMethod = function() { // code }
}()); [/syntax_prettify]
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.
[syntax_prettify linenums="linenums"]var Library = (function () {
"use strict";
var privateMethod = function() {
// code
}
return {
publicMethod: privateMehod
};
}());[/syntax_prettify]
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
[syntax_prettify]Library.publicMethod();[/syntax_prettify]
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:
[syntax_prettify linenums="linenums"]var Library = (function (library) {
"use strict";
// locally scoped object
var _ = {};
.privateMethod = function () { // code }; // public method library.publicMethod = .privateMethod;
return library;
}( Library || {} ));[/syntax_prettify]
To extend other modules:
[syntax_prettify linenums="linenums"]var Library2 = (function (library) {
"use strict";
// locally scoped object
var _ = {};
_.privateMethod = function () {
// code
};
// public method
library.newPublicMethod = _.privateMethod;
return library;
}( Library || {} ));[/syntax_prettify]