How to use Revealing module pattern in JavaScript

A small example:

var revealed = function(){
   var a = [1,2,3];
   function abc(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

in the anonymous function that is initiated to give revealed a value, a and abc are private to that function. What the function returns is an object literal with a name property and a abcfn property, which is a reference to the abc function. The abc function uses the private variable a. This can all be done thanks to the use of closures (everything within the scope of a function can be referenced by everything else in that same function).

Revealed usage:

alert(revealed.name);    //=> 'revealed'
alert(revealed.abcfn()); //=> 5 (1*2+3)

Leave a Comment