The Revealing Module Pattern
Now that we’re a little more familiar with the Module pattern, let’s take a look at a slightly improved version—Christian Heilmann’s Revealing Module pattern.
The Revealing Module pattern came about as Heilmann was frustrated with the fact that he had to repeat the name of the main object when he wanted to call one public method from another or access public variables. He also disliked the Module pattern’s requirement of having to switch to object literal notation for the things he wished to make public.
The result of his efforts was an updated pattern in which he could simply define all functions and variables in the private scope and return an anonymous object with pointers to the private functionality he wished to reveal as public.
An example of how to use the Revealing Module pattern is as follows:
varmyRevealingModule=function(){varprivateVar="Ben Cherry",publicVar="Hey there!";functionprivateFunction(){console.log("Name:"+privateVar);}functionpublicSetName(strName){privateVar=strName;}functionpublicGetName(){privateFunction();}// Reveal public pointers to// private functions and propertiesreturn{setName:publicSetName,greeting:publicVar,getName:publicGetName};}();myRevealingModule.setName("Paul Kinlan");
The pattern can also be used to reveal private functions and properties with a more specific naming scheme if you would prefer:
varmyRevealingModule=function(){varprivateCounter=0;function
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access