JavaScript: Module Pattern

The Module pattern is similar to the Prototype pattern in that it helps to encapsulate data and take variables and functions out of the global scope. However, it introduces the ability to have private variables and functions. The basic structure looks like the following:

var Example = function(){
   //private variables
   //private functions

   return{
      //public variables and functions
   };
};


The main points to note about the Module pattern are:

  • Helps create re-usable objects
  • Variables and functions are taken out of the global scope
  • Allows for public and private variables and functions
  • Functions can be duplicated in memory (unlike the Prototype) when a singleton* is not used
  • It is not as easy to extend/over-ride as the Prototype
  • Having private members can make it harder to debug

* I aim to follow up to this post with an example of this.

I have added a fuller example of this pattern over here.
If you go over to the Module example page you will see that a global Calculator object (‘calc’) is created. If you use your browser’s developer tools (on Chrome: Ctrl + Shift + I) and type ‘calc’ in the command line, you should see something like this:
Console Image
From here you can play about and call functions of the calc object.
Console output
Notice how the attempt to call private function ‘subtract’ causes an error. Keep an eye on the HTML ‘Output’ as you do some calculations, and you should see the value change after certain functions are called.

As a side-note, I am learning about these patterns through Pluralsight, although I came across this site the other day, which has an extensive list of patterns.