Introduction
In this article, I will discuss one of the best coding practices in JavaScript that is known as Module Pattern.
Module Pattern is very common in the JavaScript world with its great importance. It helps us to write clean object oriented JavaScript. Module Pattern restricts the developer to create multiple Global Variables. It is always a good practice to have less number of global variables for good performance of web application. Hence this pattern increases the performance of your website, at the same time it gives the well maintainable object oriented programing practice.
What is Module Pattern
In JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create a singleton object instead of creating instance of a class. Inside the module, the inner functions do have the static scope with the other defined variables and functions.
Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Module pattern.
A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only in the module. Methods in a module have scope and access to the shared private
data and private
methods. Hence, these methods are also called as Privileged methods.
Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format. And because of the closure principle, those privileged methods have access to the inner methods and variables of the anonymous function. We call it as a Module Pattern.
Privileged Method
In Module Pattern, you can write your private
methods, private
variables those you don’t want to expose to the other world and at the same time you will be able to write public
and privileged methods also. The great usefulness of this pattern is that you can very well access your private
methods and variables from your methods those are called as Privileged Methods.
Closure
In order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular pattern becomes very useful and powerful. Closure principle says that any inner function inside a parent function has scope to the other inner function and variables although after the parent function has returned. In Module Pattern, Privileged methods have scope to the other private
variables and methods of the module.
Self-executed Function
In Module Pattern, we create one Global Singleton Object by writing self-executed method. Self-executed method is an anonymous method that is being called by itself only. See the below code that explains how we can write self-executed method.
Example of Self-executed function
(function ( ) {
})( );
In the above code, I have one anonymous method that is declared and just after declaration it has been called by writing();
The moment we execute this JavaScript code, this method will get executed by itself only. Hence it is called a self-executed method.
Sample of Module Pattern
Having understood the idea of module pattern, self-executed method, closure now let me define the module pattern style. See the below code:
var Module = ( function ( ) {
var privateVariable = "some value",
privateMethod = function ( ) {
};
return {
privilegedMethod : function ( ) {
alert(privateVariable);
privateMethod( );
}
};
})( );
Here Module
is the Single Global Variable that is exposed to the document. We are declaring, calling one anonymous method and assigning it to Module
variable. Now we can call privilegedMethod
by writing Module.privilegedMethod();
internally privileged Method of module can access its private
variable and private
method. Because, they come under their static
scope. If we have any data or method that we don't want to expose, we can put them in private
methods.
We can also write the above code in a different manner, see the below way:
var Module = ( function ( ) {
var
privateVariable = "some value"
,privateMethod = function ( ) {
}
,retObject = {
privilegedMethod : function ( ) {
alert(privateVariable);
privateMethod( );
}
};
return retObject;
})( );
Public
Methods don't have access to Private
Methods and variables, only the privileged method inside the Module can have access because of the closure. Let's see it.
We can create the public
methods in the Module by the below method:
Module.publicMethod1 = function () {
Module.privateMethod ( );
Module.privilegedMethod ( );
}
In the above example, the public
method publicMethod1
that we augmented into the module doesn't have access to the privateMethod
of the Module
object. In order to access the private
Methods or Variables, we can call the privileged method of the Module inside the public
. This is the benefit of this pattern. In our above example, we could call Module.privilegedMethod()
.
Example of Module Pattern
I have created one sample .NET application, the same is attached here in this article. In that .NET Application, I have created one Module pattern JavaScript function. Let's discuss the same function. See the below code snippet:
var SearchEngine = (function ( ) {
var luckyAlgo = function ( ){
return Math.floor(Math.random()*11);
}
return {
getYourLuckyNumber : function ( ){
return luckyAlgo();
}
}
} ) ( );
In the above code snippet, I have one Global variable called SearchEngine.
A self-executed anonymous method is assigned in to the SearchEngine
variable.
SearchEngine
has one Private
method luckyAlgo
and one Privileged Method getYourLuckyNumber.
The Privileged method is being returned by encapsulating in an anonymous object. SearchEngine
can be accessed globally that will have one Privileged method only. And the Privileged method can call its local method luckyAlgo
, because of the principle of Closure. In the above example, if you call getYourLuckyNumber
method then it will return one random number.
Creating Sub Modules
We can create the sub-module as well by augmenting our module object with a sub module. It will be again in the same module pattern fashion. See the below example, I have created one more subSearch
object inside the SearchEngine
object by following the same module pattern.
SearchEngine.subSearch = (function ( ) {
var defaultColor = "Orange";
var myColorAlgo = function (num) {
switch(num){
case 1:
defaultColor ="Green";break;
case 2:
defaultColor ="Black";break;
case 3:
defaultColor ="Yellow";break;
case 4:
defaultColor ="White";break;
case 9:
defaultColor ="Red";break;
}
};
return {
getYourLuckyColor : function(){
myColorAlgo(SearchEngine.getYourLuckyNumber());
return defaultColor;
}
};
})();
In the above example, if we call the getYourLuckyColor
method, then it will give you one color name based on the random number. I know these methods are not much practical however, I could think of them only in order to explain the concept.
Extending Modules
We can extend the existing modules by wrapping it inside one new module. By doing that, we can very well access / override the existing method of the old module. See the below code:
var Module1 = ( function (oldModule) {
var
parent = oldModule;
parent.privilegedMethod = function ( ){
};
var privateMethod2 = function ( ) {
parent.privilegedMethod();
parent.publicMethod1();
}
return {
newMethod : function ( ) {
}
};
} )(Module);
In the above example, I have described the advanced features of Module pattern where one can re-use the existing module by extending, augmenting and overriding.
I have passed the old existing Module
object (see above in module pattern section, we have created one Module object) while calling our anonymous method and then I have assigned it into a local variable called as parent
. Now, I can access the public
/privileged methods of the parent Module
in my private
, privileged and public
method of new Module1
object.
The sweetness of this pattern comes when I can also override the existing method of the old Module
. And you can see, I have overridden the privilegedMethod
of the Module
object. Similarly, I could have overridden the public
method of the Module
object
Conclusion
I have given very simple examples. However, one can learn this pattern and create very complex coding also. You must be aware of YUI this is a great JavaScript library It is written on the principle of Module Pattern only. In my personal experience, I used to write JavaScript code more in Module Pattern and I enjoy it a lot. Now this pattern is my favorite one and I have lots of fun also. Hope this article will help you. Please give your comments and suggestions.