As Douglas Crockford wrote on Javascript: the good parts, a module is a function or object that presents an interface but hides its state and implementation.
I used indeed the module pattern once I needed encapsulation, i.e. to have a class method that had a public interface but that hid implementation details.
In addition to encapsulation I needed a costructor with arguments, so I added it too in the following code, which implements the module pattern with a constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function Module(name) { this.name = name; } Module.prototype = (function() { var i = 0; function myPrivateFun() { console.log("private " + i++); } function myPublicFun() { myPrivateFun(); console.log(this.name); } return { publicFun: myPublicFun }; })(); var m = new Module("john"); m.publicFun(); // private 0 John |
The constructor is defined as it is usually done in Javascript.
The module pattern has been used in the prototype implementation, where we have
- privateFun which is a private method, visible only from publicFun
- publicFun which is a public method, externally visible
- the return which returns an object whose members are externally visible, and so where we put public method
We have used in the code:
- immediately invoked function expressions
- closures
Immediately invoked function expressions
IIFE (immediately invoked function expressions), like
1 2 |
(function() { })(); |
make so that the function is immediately executed, and that the result is returned with the return we talked about above
Closures
Closures allow functions defined in a certain scope to continue to have access to the variables declared in that scope even when the outer function which defined that scope has terminated. In the example above we see how we access the variable i even when the outer function has ended its life cycle.