Again with the Module Pattern – reveal something to the world

Not too long ago I was raving about the beauty of the Module Pattern in JavaScript and the annoyance I felt with it when it comes to repetition of long namespaces when calling or reading public methods and properties from other public methods and properties.

To recap, the “classic” Module Pattern means you define a variable as an anonymous function that gets immediately called with (). You define private functions and variables and return your public variables and functions as properties and methods of an anonymous object:


var classicModulePattern = function(){
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  }
  return {
    publicVar:2,
    publicFunction:function(){
      classicModulePattern.anotherPublicFunction();	  
    },
    anotherPublicFunction:function(){
      privateFunction();
    }
  }
}();
classicModulePattern.publicFunction();

The beef I had with that is that you need to repeat the name of the main object when you want to call one public method from another or access public variables. The other bit I was annoyed about is having to switch to object literal notation for the things you want to make public.

Inspired by the comments on the blog post on the YUI about the module pattern and pubstandards, I started advocating using a named object called pub to append methods and properties to before returning it. That way you can call public methods via the pub.methodName shortcut notation instead of repeating the main name:


var namedObjectModulePattern = function(){
  var pub = {};
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  };
  pub.publicVar = 2;
  pub.publicFunction = function(){
    pub.anotherPublicFunction();	  
  };
  pub.anotherPublicFunction = function(){
    privateFunction();
  };
  return pub;
}();
namedObjectModulePattern.publicFunction();

During a Q&A session in a training in Hongkong yesterday I showed this to Douglas Crockford and asked him what he thinks of it. He didn’t mind the idea, but considered even the pub object redundant.

There is another option which I am hereby calling the Revealing Module Pattern. In this permutation you simply define all your functions and variables in the private scope and return an anonymous object at the end of the module with pointers to the private variables and functions you want to reveal as public:


var revealingModulePattern = function(){
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  };
  var publicVar = 2;
  function publicFunction(){
    anotherPublicFunction();	  
  };
  function anotherPublicFunction(){
    privateFunction();
  };
  // reveal all things private by assigning public pointers
  return {
    publicFunction:publicFunction,
    publicVar:publicVar,
    anotherPublicFunction:anotherPublicFunction
  }
}();
revealingModulePattern.publicFunction();

This keeps the syntax of the whole script consistent and makes it obvious at the end which of the functions and variables can be accessed publicly. The other benefit is that you can reveal private functions with other, more specific names if you wanted to.


var revealingModulePattern = function(){
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  };
  var publicVar = 2;
  function publicFunction(){
    anotherPublicFunction();	  
  };
  function anotherPublicFunction(){
    privateFunction();
  };
  // reveal all things private by assigning public pointers
  return {
    init:publicFunction,
    count:publicVar,
    increase:anotherPublicFunction
  }
}();
revealingModulePattern.init();

You can even return values as the public properties by calling the functions in the anonymous object:


var revealingModulePattern = function(){
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  };
  var publicVar = 2;
  function publicFunction(){
    anotherPublicFunction();	  
  };
  function anotherPublicFunction(){
    privateFunction();
  };
  function getCurrentState(){
    return 2;
  };
  // reveal all things private by assigning public pointers
  return {
    init:publicFunction,
    count:publicVar,
    increase:anotherPublicFunction,
    current:getCurrentState()
  }
}();
alert(revealingModulePattern.current) 
// => 2
revealingModulePattern.init();

Of course the example names here are far from what I would use in a real script, but it shows the power of this pattern.

22 Responses to “Again with the Module Pattern – reveal something to the world”

  1. klauskomenda.com » JavaScript Programming Patterns Says:

    [...] azy Function Definition Pattern by Peter Michaux Christian again, describing what he calls Revealing Module Pattern No Comments Posted in Coding, [...]

  2. klauskomenda.com » Agent YUI: Introduction Says:

    [...] e Rules. One word regarding the examples to come during this series: I am going to use the Revealing Module Pattern (courtesy of Christian Heilmann) to write the example-specific JavaScript cod [...]

  3. Juergen Riemer Says:

    Thanks for your articles Chris, yet if I want to print them the left and the right menu overlap the text. Did I oversee an expilicit print button?

  4. Craig Says:

    That’s a brilliant idea – and even cleaner than before! It also has several other benefits:

    - a property or method can be changed to public or private very easily.

    - you could have two or more public values for the same property or method, e.g. Initialise and Init.

    - you could determine what property/method gets assigned at runtime, e.g.
    PublicMethod: (condition ? Method1 : Method2)

    Looks like I’ll be re-writing my modules. Again!

  5. Patrick Fitzgerald Says:

    I like it! It’s definitely easier to see what is going on with this new pattern. It will still be a bit hard for the novice to understand, but better than before.

  6. Thomas Messier Says:

    As far as the annoyance of having to repeat the namespace, couldn’t you just use the “this” keyword instead? That’s what I do and it seems to work OK. But maybe in more complex situations the references kind of break down? Or maybe I’m just missing something, would be curious to know.

  7. Andy Beeching Says:

    Top article Chris, these evangelical efforts are brilliant to educate the JS community at large on OO voodoo! I’m going to base my scripts on this pattern from now on (where appropriate of course). Can I suggest you add some extra styling to the code samples on the page? They are hard to pick out from the surrounding text… a border and a light background color would go a long way to alleviate this. Great content nonetheless!

  8. Javascript com PadrĂ£o « Jorge Eduardo Says:

    [...] things he did not like about the module pattern, Christian came up with something that he calls Revealing Module Pattern. As the name indicates, it is related to the Module Pattern, but might be a bit more structured and [...]

  9. Le coin d’Anthony » Blog Archive » Javascript, singleton et Module Pattern… Says:

    [...] trouve pas mal d’articles sur le net qui traitent du même sujet, comme celui-ci, ou encore celui-là. Classé sous Javascript , Laisser un [...]

  10. Wait till I come! » Blog Archive » Example of an unobtrusive, lazy-loading badge using the Twitter API Says:

    [...] am using the revealing module pattern to keep code short and avoid global callback methods. However, there is a slight Opera oddity with [...]

  11. Rytis Daugirdas Says:

    Nice article, quite an improvement of code readability over the original.

  12. protofunc ( » Ineffizienter jQuery-Code) Says:

    [...] schaue recht gerne in den JS-Code anderer. Hierbei fällt einem neben der Tatsache, dass saubere Organisation von JS selten vorkommt, vor allem die ineffiziente Verwendung von jQuery auf. Hier [...]

  13. Arjan Eising » Fronteers 2008, things I liked Says:

    [...] you can write it in your application as one function. Then call it every time you need it. You then reveal the re-usable parts out of the script’s scope, because some other script on your website might use it as [...]

  14. protofunc ( » jQuery UI Widgets erweitern: Am Beispiel der UI-Canvasmap ) Says:

    [...] Das Functional-Pattern ist eine sehr schöne und einfache Art seinen Code zu organisieren. Wie der Name bereits sagt wird eine Funktion verwendet, um seinen Code zu kapseln. Die bekannteste, aber wohl zugleich wohl komplizierteste, Variante stellt das sog. Module-Pattern dar, mit welchem Singeltons erstellt werden können. Ich persönlich bevorzuge hier die Syntax des sog. Revealing Module Pattern. [...]

  15. Module Pattern for Javascript :: BrianBal.com Says:

    [...] that bugged me about using this pattern. To alleviate this annoyance I did some googling and found Again with the Module Pattern. This article will give you an idea about how useful the Module Pattern can [...]

  16. links for 2009-01-11 « pabloidz Says:

    [...] Again with the Module Pattern – reveal something to the world Wait till I come! (tags: javascript) [...]

  17. Frank Young Says:

    Awesome stuff Chris. I just started on OO JS a month ago (I’ve been an Actionscript, PHP, Java) guy for some years – I shied away from anything complex in javascript because it always seemed simplistic and annoying language – but with all the work done with the various frameworks and with people like you innovating new design patterns – I have a new respect and love for the language and its abilities. Thanks again!

  18. Chris Kapilla Says:

    I have been on a quest to find the optimal JS module pattern, and here it is! Thanks so much.

  19. Chris Kapilla Says:

    It seems your code samples have flipped the usage of semicolons: putting them after ‘internal’ function declarations where they are unnecessary, and not putting them after the return statement where they are expected. I trust JSLint to get things like this correct, and it dutifully complains when presented with your samples (discovered after it complained about my code based on your samples). Because all the JS syntax ambiguities just muddy the water, I think it is best to be ‘pixel perfect’ in this regard. Thanks.

  20. alexsandro_xpt (Alexsandro) Says:


    Revelando algo para o mundo sobre Module Pattern. Olha isto -> [link to post] #javascript #designpattern

    Posted using Chat Catcher

  21. jlbruno (Jeff L) Says:


    i don’t know how i’ve never seen @codepo8’s revealing module pattern: [link to post]

    Posted using Chat Catcher

  22. ChristopherBlum (Christopher Blum) Says:


    Another great article on the module pattern by @codepo8 (thx for sharing) [link to post]

    Posted using Chat Catcher

Leave a Reply

Wait till I come! is the blog of Christian Heilmann , a developer evangelist living and working in London, England. Download vcard.

Feed me, Seymour: Entries (RSS) and Comments (RSS).