The previous articles explained the Prototype Pattern. You can read them at the following links:
- Understanding Prototype Pattern in JavaScript
- Understanding Prototype Pattern in JavaScript: Part # 2
The Revealing Module Pattern allows us to create:
- Singleton object
- Private Public behavior of functions and properties in the object.
Let us consider the usual code we write. We also know it as functional spaghetti code.
var basicSalary;
var salary;
function CalculateSalaray(basicSalary) {
salary = basicSalary * 10;
}
function PrintSalaray() {
alert("Salary is " + salary);
}
CalculateSalaray(200);
PrintSalaray();
There is nothing wrong in the code snippet above. However:
- It is hard to maintain when functionality grows
- It is hard to debug
- It is hard to test
In the Revealing Module Pattern all code is placed inside a function represented by a variable. This is a self-executed function.
The Revealing Module Pattern allows us to:
- Create public private members
- Make code more readable
In this pattern we put all functions and variables inside the object. In the above case everything would be encapsulated inside a salary object. To make anything public we need to make them part of a return statement.
var salaray = function () {
//Private
var sal;
function calculateSal(basesal) {
sal = basesal*1000;
}
function printSal(basesal) {
calculateSal(basesal);
console.log(sal);
}
//Public
return {
PrintSalary: printSal
};
}();
salaray.PrintSalary(2000);
In the snippet code above we have two private functions. One private function is exposed as public in the return statement. Since the object is wrapped as a self-executable function hence it works as a singleton. We can call public functions on the object itself.
If we want to remove a singleton then the following two steps need to be done:
-
Remove self-executable code
-
Create a new object using the new operator
So the object salary above can be modified as in the following. Now it will have a private public property but it would not act as a singleton.
var salaray = function () {
//Private
var sal;
function calculateSal(basesal) {
sal = basesal*1000;
}
function printSal(basesal) {
calculateSal(basesal);
console.log(sal);
}
//Public
return {
PrintSalary: printSal
};
};
var mysal = new salaray();
mysal.PrintSalary(789);
var mysal1 = new salaray();
mysal.PrintSalary(100);
In the code above the salary object is not a singleton and has private and public functions. In many terms the Revealing Module Pattern can be considered as one of the best JavaScript patterns. Three advantages of the Revealing Module Pattern are as follows:
-
Creates a Singleton
-
Gets Private or Public method behavior.
-
Better readability of code
I hope you find this article useful. Thanks for reading.
Previous article: Understanding Prototype Pattern in JavaScript: Part # 2