Module pattern allows to emulate the concept of classes in Javascript. It allows to create private methods and variables along with their public counterparts inside the same class, thus shielding particular parts of the class from the global scope.
Let’s look at an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
var module = function () { var random = Math.random(); return { showRandom: function () { console.log(random); } }; }; // Usage: var m1 = new module(); m1.showRandom(); var m2 = new module(); m2.showRandom(); //error - can't access the private variable 'random' from outside console.log(m2.random); |
Here, the private variable ‘random’ is encapsulated and any code outside of the module can’t access this variable. The functions and properties inside the ‘return{ }’ are exposed publicly and anything outside of ‘return{ }’ are considered private.
This is can also be written as a self-contained module:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var module = function () { var random = Math.random(); return { showRandom: function () { console.log(random); } }; }(); // Usage: module.showRandom(); |
Notice the () at the end of the module definition? This will create an instance and return it in the global variable ‘module’.
Passing arguments
A variation of this pattern allows to import modules and alias them locally by passing it as arguments to the anonymous function.
Let’s look at another example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var module = function (jq) { var getValue = function (elem) { console.log(jq(elem).html()); } return { getHeader: function () { getValue("#header"); }, getFooter: function () { getValue("#footer"); } } } (jQuery); // Usage: module.getHeader(); module.getFooter(); |
Here, the global variable jQuery is passed as ‘jq’ into the module making it local inside the scope of the module.
Reference:
From the excellent online book by Addy Osmani:
Learning Javascript Design Patterns