The Module Pattern

This pattern is used to mimic classes in conventional software engineering and focuses on public and private access to methods & variables. The module pattern strives to improve the reduction of globally scoped variables, thus decreasing the chances of collision with other code throughout an application.

The module pattern is, by far, the most commonly used design pattern and widely accepted in a number of large projects such as jQuery, Dojo, ExtJS and YUI.

“I’m currently in the process of writing a large-scale JavaScript application based on this pattern, and I have to say, it’s a delight.”
- Brian Cray

This article is part of a series called JavaScript Design Patterns.

Advantages

Disadvantages

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
( function( window, undefined ) {
// normally variables & functions start with a lowercase letter but with modules, that is not the case.
// The general tradition is to start them with a capital letter instead.
function MyModule() {
// `this` refers to the instance of `MyModule` when created
this.myMethod = function myMethod() {
alert( 'my method' );
};
// note that we still use a function declaration even when using a function expression.
// for more information on why, check out: http://kangax.github.io/nfe/
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
}
// expose access to the constructor
window.MyModule = MyModule;
} )( window );
 
// example usage
var myModule = new MyModule();
myModule.myMethod(); // alerts "my method"
myModule.myOtherMethod(); // alerts "my other method"

Another example of the module pattern that exposes the module a little differently and makes use of a shared private cache. This method encourages more of an object creation approach where we can optimize performance by being efficient with shared storage.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
var MyModule = ( function( window, undefined ) {
 
// this object is used to store private variables and methods across multiple instantiations
var privates = {};
function MyModule() {
this.myMethod = function myMethod() {
alert( 'my method' );
};
 
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
 
}
 
return MyModule;
} )( window );
 
// example usage
var myMod = new MyModule();
myMod.myMethod(); // alerts "my method"
myMod.myOtherMethod(); // alerts "my other method"

Additional Resources

http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
http://macwright.org/2012/06/04/the-module-pattern.html
http://briancray.com/posts/javascript-module-pattern
http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

Other Common JS Patterns

The Module Pattern
The Revealing Module Pattern
The Singleton Pattern
The Observer Pattern
The Mediator Pattern
The Prototype Pattern
The Facade Pattern
The Factory Pattern

Updates

8 responses!

Ben Truyman said: (8 months ago) Reply

The code example looks a little off. Typically the module will export itself in some way.

For example:

window.MyModule = (function (window) {

  var privates;

  function MyModule() {
    ...
  }

  return MyModule;

})(window);

Or even:

function MyModule() {
  var module = {};

  module.method = function () {};

  return module;
}
    Ben Truyman said: (8 months ago) Reply

    Whoops, forgot to wrap my code with a pre. :-/

      carldanley said: (8 months ago) Reply

      No worries, I added the pre tag for you. I expose the module on line line 20 but I’m thinking I might patch the article to show a few different ways you can expose the module.

        Ben Truyman said: (8 months ago) Reply

        Thanks for fixing my comment. On line 20 of the first example, you exposed an instance but not the module constructor itself. In the new example you added, others that are outside of the closure can instantiate MyModule. Of course you could just window.MyModule = MyModule;

        The pattern I typically use is:

        (function (global, undefined) {
        
          function MyModule() { ... }
        
          global.MyModule = MyModule;
        
        })(this);

        In the above, thisin the IIFE invocation usually refers to the global object (window in the browser, exports in Node.js). Which is only really useful for code that is not necessarily browser-specific. And I say it “usually” refers to the global object because if you happen to include that snippet inside of some other context, it may not be the case.

          carldanley said: (8 months ago)

          I see where you’re going with this and I have to agree with you. I generally initialize a module only one time and bind it to something but you’re point (I think) is that we should be exposing the constructor so we can have public access to new instantiations. That said, excellent call. I’ll tweak the example to expose access to the constructor.

      carldanley said: (8 months ago) Reply

      I ended up patching the article above with an updated example. Let me know your thoughts if you have the chance.

Eric Mann said: (8 months ago) Reply

I both agree and disagree with the point on unit testing. On the one hand, it’s true that MyModule will be difficult to test since it’s not exposed outside the closure. But the public methods it exposes are available outside of the closure. That bullet point should be more a caution to developers utilizing the pattern that their API should be publicly exposed (since a private API isn’t really an “interface” to begin with) rather than a disadvantage of the pattern.

    carldanley said: (8 months ago) Reply

    Excellent point!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>