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.

11 Responses to “Again with the Module Pattern - reveal something to the world”

  1. 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?

  2. 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!

  3. 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, [...]

  4. 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.

  5. 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.

  6. 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 [...]

  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.

Leave a Reply

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

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