Grow your CSS skills. Land your dream job.

How Do You Structure JavaScript? The Module Pattern Edition

Published by Chris Coyier

JavaScript is interesting in that it enforces no particular structure upon you. "Bring Your Own Organization", if you will. As I write more and more JavaScript in web app sites, this becomes more and more interesting. How you structure your JavaScript is very important because:

  1. Done right, it makes code easier to understand for others and yourself re-visting your own code.
  2. Having a decided-upon structure helps keep future code clean and encourages your declared best practices.
  3. It makes your code testable.

Before I go any further, let it be known that I am far from a master of JavaScript. There are a lot of smart folks in the JavaScript world that have been doing and talking about this for longer than I knew what a div was.

This has been a topic in my mind lately because I've been writing a lot more JavaScript for CodePen, which is very JavaScript heavy. We've been using the "Module Pattern" since the beginning and it's been serving us quite well I think.

Then I posted this article about the making of the Treehouse ad, and within it I also used the Module Pattern for the JavaScript there. Louis Lazaris chimed in that this is how he's been liking to write JavaScript lately too, and started a bit of a discussion. Louis followed it up with an article explaining his preferred structural pattern.

The Concept

It's easier to understand concepts like this if there is an example to build from. Let's say we're building a news widget. It lists some news articles, and has a button in which you can load more news articles.

The Module

Humble beginnings:

var NewsWidget = {

};

Just an object. I like my JavaScript variables starting with a lowercase character, but Modules get an uppercase first character. Just a convention that helps code readability.

Settings

The news widget will likely have some significant numbers associated with it (e.g. how many articles in it). Also, some significant elements (DOM nodes) that will need to be accessed regularly.

There will be a number of sub-functions of this module that do small specific things. Many of those may need access to these settings and "cached" elements. So, we'll make the settings available to each of them.

var s,
NewsWidget = {

  settings: {
    numArticles: 5,
    articleList: $("#article-list")
  }

};

We'll get to the sub-function access in a second.

Init Function

To "kick things off" we'll have just one function be called. This will be consistent across all modules, so you know exactly where to look when you start reading the code and figuring out what happens when.

var s,
NewsWidget = {

  settings: {
    numArticles: 5,
    articleList: $("#article-list"),
    moreButton: $("#more-button")
  },

  init: function() {
    // kick things off
    s = this.settings;
  }

};

The first thing the init function will do is set the variable s (which we declared at the same level as the Module) to be a pointer to the settings. Because of where s was declared, this means all sub-functions of the Module will have access to the settings. Nice.

Binding UI Actions

Alex Vasquez set up a convention for us at CodePen where we would have a function just for binding the UI events. You never write any code that "does stuff" when you bind, you just do the binding and then call another appropriately named sub-function.

var s,
NewsWidget = {

  settings: {
    numArticles: 5,
    articleList: $("#article-list"),
    moreButton: $("#more-button")
  },

  init: function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions: function() {
    s.moreButton.on("click", function() {
      NewsWidget.getMoreArticles(s.numArticles);
    });
  },

  getMoreArticles: function(numToGet) {
    // $.ajax or something
    // using numToGet as param
  }

};

Combining Files

Chances are the news widget isn't the only JavaScript you'll have on a page. There will be lots of Modules you'll need to load. Perhaps the news widget is on every page of your site, so belongs in a global.js file. This global.js file will ultimately be a a bunch of Modules concatenated, and then a big kick off party.

There are all kinds of ways to handle this concatenation stuff. It could be a dev tool like CodeKit and it's ability to do appends/prepends. It could be some fancy Grunt.js build script thing.

At CodePen we use Ruby on Rails and it's asset pipeline. So for us, the global.js file would be something like:

//= require common/library.js

//= require module/news-widget.js
//= require module/some-other-widget.js

(function() {

  NewsWidget.init();

  SomeOtherModule.init();

})();

That's All Folks

Pretty darn satisfying way to write JavaScript, I think. It satisfies the three points I made about the importance of structure.

Regarding the testing point, I know that wasn't discussed much, but I'm sure you can imagine how having smaller specific functions in change of specific tasks are easier to write assertions for. That's how most JavaScript testing is done (e.g. Jasmine). For instance, in some form of code or another: "I assert that when this function gets this value this other thing happens and is equal to some other value."

This is the tip of the iceberg. I've only just started it, but Learning JavaScript Design Patterns (free to read online!) by Addy Osmani looks to be going a lot deeper down this rabbit hole.

Comments

  1. Permalink to comment#

    You should probably remove the “function()” from the second line of every code example (except the first and last ones). :-)

  2. Permalink to comment#

    Great explanation, man…

  3. Permalink to comment#

    Awesome sauce. Pretty similar to what I have been doing but cleaner. I really like how to do the settings. Thanks

  4. Scottie
    Permalink to comment#

    I’d recommend looking into Marionette (http://marionettejs.com/). I like using their modules/views/routers/controllers even if I’m not using Backbone to interact with a REST back end. Marionette gives me a sane way to structure code. It also takes care of some of the boilerplate code and memory management issues.

    The developer Derick Bailey also gives a nice JSFiddle to get you started (http://jsfiddle.net/derickbailey/M5J8Q/). It’s uber simplified but a good starting point if you want to learn/dabble.

  5. Jeremy T
    Permalink to comment#

    If you use that same “s” variable for the settings for each module, and then import them all into the same global.js, wouldn’t they conflict with each other?

    • Michael
      Permalink to comment#

      That is a good catch IMHO, they’d better use some module loader (require.js or equivalent) or use an auto-executing function ( the

      (function(namespace) {
      ...
          namespace.NewsWidget = NewsWidget;
      })(namespace);
      

      to enclose local variables.

      They’d rather use an existing module pattern (once again, AMD style) then re-coding it.

    • atmin
      Permalink to comment#

      No, because the modules are initialized sequentially. But I would use ‘this.settings’ (or local shortcut var, if I need ‘this.settings’ many times) in place of ‘s’.

    • @atmin That’s what got me too.. why pollute the global namespace for a shortcut? Why not set the s var local and use it as a shortcut, or just skip the semantics and use s as the settings object?

    • Jeremy T
      Permalink to comment#

      Fine, they’re initialized sequentially. But I thought the reason that s was declared outside the module instead of as a local variable inside the init function was so other methods in the same module could more easily access the settings in the future. If NewsWidget.getMoreArticles references s, it’s going to be looking at the wrong settings.

      Actually, I think in the example code, inside the event handler, that would probably throw an error because it references s.numArticles and would be triggered after other modules had been initialized.

    • Jeremy T
      Permalink to comment#

      Here’s an example of what I’m talking about: http://codepen.io/jetpacmonkey/pen/gkmei

    • Brendan
      Permalink to comment#

      Agree with Michael generally. I used to write my modules like demonstrated in the post and quickly ran into name collision issues. I now write my modules using the self-executing function pattern, thus providing “encapsulation” for private variables/methods/etc to the module. Try something like:

          var NewsWidget = (function(){
              var s = { 'internal' : 'settings' },
              me = {};
      
              function setupBindings() {
                  //do UI bindings
              }
      
              me.init = function() {
                  setupBindings();
                  //do other important setup things
              }
      
              return me;
           }());
      

      FWIW, Indentation doesn’t seem to be working properly…or I’m missing something about how to format code in a <pre>

    • What Brendan said :)

    • Jeremy T
      Permalink to comment#

      The indentation is fine. The preview seems to be broken.

    • Devon
      Permalink to comment#

      Global variables are one of the worst anti-patterns in any programming language. This is almost always the first thing you are taught in a CS-101 course at any university. JavaScript makes using this anti-pattern easy and almost goads you into it. Why? Because you often find yourself in the middle of a closure scope with no way of accessing a variable you need, so you make a variable in an outer scope. Chris said it himself, “we’ll make the settings available to each of them [sub-functions].” The best thing that you can do to your global-scope variables is to declare them “const” and make them immutable. If JS starts yelling at you about illegal access, you know you are using it incorrectly. The other solutions are listed in some of the other comments. Use namespacing.

  6. Michael
    Permalink to comment#

    Something seems strange with your module pattern: you declare the settings object, and assign articleList to a jQuery object. That means that your DOM has to be ready when you include this javascript file. If that’s true, what’s the purpose of having an init function that bind events to the DOM ?

    • Load all scripts at the bottom, DOM is ready when you call the script.

    • It would probably be more flexible if instead of having a fixed ID for the list of articles, it could be passed as a parameter to init()

    • Mladen
      Permalink to comment#

      It would probably be more flexible if instead of having a fixed ID for the list of articles, it could be passed as a parameter to init()

      Agreed. Exactly what I do, but I do like to have default value that I can override.

  7. Permalink to comment#

    Jeremy: I believe that this wouldn’t happen. The ‘s’ is also referencing ‘this’ which, I believe, keeps things from over-writing one another thanks to the lexical scope of functions. Of course, if I’m wrong, I stand corrected.

    • Jeremy T
      Permalink to comment#

      the this is on the right side of the equals. The s variable that’s actually being assigned to has global scope (which was the whole reason that it was declared outside of the module), which means, unless Ruby on Rails is doing something fancy, the second module’s init would overwrite the settings from the first, and any later calls to a function inside the first module that uses s would be referencing the settings for the second module.

  8. Nelson Polanco
    Permalink to comment#

    Could this also be written like this? `

    var NewsWidget = function(){
         this.setting = { ... }
    }
    
    NewsWidget.prototype ={
        init: function() { ... },
    
        bindUIActions: function() { ... }
    } 
    
    // Usage var nw = new NewsWidget();
    

    More OOP I guess?

    • Permalink to comment#

      I think that yes, it could be written like that. Chris’ example focuses on stricter namespacing. Where ‘NewsWidget’ is a master class with sub-classes attached to it: ‘settings’, ‘init’, etc.

    • Permalink to comment#

      Actually the methodology which Chris has used conforms Singleton design pattern & it’s very commonly used amongst OOP languages.

      You can look on internet for situations where exactly you are supposed to use it.

  9. Permalink to comment#

    Thanks for mentioning my post, Chris.

    For those interested, I highly recommend a few of the comments posted on mine, which gave some great suggestions. I particularly liked the one from Maciej Baron:

    http://www.impressivewebs.com/my-current-javascript-design-pattern/#comment-32835

  10. Permalink to comment#

    This is not Module Pattern, this is a simple Object Literal, Module Pattern is a bit more than that, and that bind function is not really a good way do develop, something like that: https://gist.github.com/4504091

  11. Permalink to comment#

    This gist represents a Module App: https://gist.github.com/4504159

  12. Permalink to comment#

    I use similar approach but using function (due to autoinitialization). It can be easy adjusted to use it as a constructior:

    
    /**
     * @name someFunction
     * @author 
     *
     * Basic usage:
     * someFunction();
     *
     * additionally you can use methods like someFunction.methodName();
     *
     * Advanced usage:
     * someFunction({
     *      "additionalOption": "thatCanOvervriteDefaults"
     * });
     */
    function someFunction(opts) {
        //assign _root and config private variables
        var _root = this;
        var _cfg = $.extend({
            "someOption":       "some value"
        }, opts);
    
        /*
            INITIALIZE
        */
        this.init = function() {
            //some code
            _somePrivateMethod();
            _root.somePublicMethod();
        }
        /*
            Some Private Method (no "this")
        */
        _somePrivateMethod = function() {
            //some code
            console.log("_somePrivateMethod");
        }
        /*
            Some Public Method
        */
        this.somePublicMethod = function() {
            //some code
            console.log("somePublicMethod");
        }
        /*********************
         *   AUTO INITIALIZE
         **********************/
         this.init();
    }
    
    //declaration and initialization of someFunction
    someFunction();
    
    //someFunction._somePrivateMethod();
    //returns: TypeError: someFunction._somePrivateMethod is not a function
    
    //someFunction.somePublicMethod();
    //returns: "somePublicMethod"
    
  13. Permalink to comment#

    You can see it on jsFiddle:
    * standard example (single, auto init) – http://jsfiddle.net/nightman/jxZ5n/1/
    * example with multiple instances, no auto init – http://jsfiddle.net/nightman/B8ECk/1/

    Regards

  14. jeanclaude
    Permalink to comment#

    Thanks for sharing, i use the same method but as a singleton , have look at this :

    http://robdodson.me/blog/2012/08/08/javascript-design-patterns-singleton/

  15. Permalink to comment#

    I’m nowhere near being a JS pro. I did learn about this pattern from a few coworkers when we were working for a big client about 6 months ago. Since that time, this is how I architect all of my JS. There’s quite a few benefits to it: 1) You can store each module separately in your CMS,and concatenate upon build. 2) If you’ve written modular HTML and CSS, you can pair functional modules with presentation modules. 3) when you use the pattern consistently, it’s easy to create JSON with it.

    The ‘Advanced’ approach which I learned is that you can create an object representing all your modules and assign it to the window, and then create a ‘master’ init to run your modules on document ready.

    window.paceaux = {
    this.init = function(){
    NewsWidget.init();
    ArticleWidget.init();
    },
    NewsWidget ={
    //blah code
    this.init= function (){
    }
    },
    ArticleWidget= {
    this.init = function (){
    }
    }
    };
    //———–
    //Document ready
    //
    $(function () {
    window.paceaux.init();
    });

  16. The main problem with this is that it’s very monolithic in that it has hard-coded dependencies on the DOM, it is a singleton so you cannot have multiple widgets per page, and it would be difficult to test.

    The style I personally favour for these type of things is the style you see in the bootstrap plugins. That is:

    you wrap everything in a self-invoking function
    inside that have a constructible object which has all the widget’s logic.
    dependencies are passed into constructor, meaning unit testing becomes much easier and you have can multiple widgets per page

    You can also very simply create a jQuery plugin and declarative data-* API from this because all your logic is wrapped in a neat object. It’s basically boilerplate code, and it makes things very flexible.

    I’ve prepared an example fully working widget, which shows exactly what I mean on codepen. It’s heavily commented in the JS so everyone should be able to follow along. It demos multiple widgets on one page too :)

  17. arnold
    Permalink to comment#

    awesome, I hope there will be more of this discussion..

    theres a lot of js pattern that can be used although sometimes we should know it make sense to use a pattern

  18. Permalink to comment#

    Your structure is correct, but it needs a few more things before it’s really a module, i.e. encapsulating private members, exposing a public API and namespacing. I highly recommend you read the original module pattern post by Douglas Crockford.

    In essence you will have a self-executing function with private members:

    News = function() {
       var foo = 'bar';
       var _init = function() {
          // do init stuff here
       }
       function setupBindings() {
          // do jQuery bindings
       }
    }();
    

    …that exposes with a public API:

    News = function() {
       var foo = 'bar';
       var _init = function() {
          // do init stuff here
       }
       function setupBindings() {
          // do jQuery bindings
       }
       return {
          init: _init
       }
    }();
    

    …that can be enabled on DOM load like this:

    $(document).ready(News.init);

    or like this if _init accepts parameters:

    $(document).ready(function(){
       News.init('#news_sidebar');
    });
  19. Permalink to comment#

    This seems like a simple way to begin to wrap my head around writing modularized code.

    Also, I hadn’t seen Addy’s book, thanks for the reference!

    small typo:
    You forgot an “S” in Addy’s last name.

  20. May I suggest you to look at BEM methodology.

    BEM is a way to organize your code to simplify process of development and future support.

    There also was a set of articles about BEM at SmashingMagazine. And project structure was described at part 3.

  21. This looks like a good way to code.
    The { spam: eggs } looks like a dictionary to me.

    Does this wok with pure JS?

  22. Permalink to comment#

    That was excellent ! just as always …

  23. Simon Davies
    Permalink to comment#

    I have some things similar but this is how at the moment I do mine, if bad, better ways etc please feel free to advise.

     /********
      *
      * Page Specific / Site Specific JS File
      * File Saved as: CustomJS.js
      *
      ********/
    ;(function(window){
       "use strict";
       var varName = function(methodName){
       this.data = {
         reqMethod : (typeof methodName !=='undefined') ? methodName : false
       }
    
       this.GenericJS = new GenericJS();
    
       this.init();
     };
     
       var o, gen;
     
       varName.prototype.init = function(){
          o = this.data, 
          gen = this.GenericJS;
          //-- dynamically call the required method on page call
          if(o.reqMethod!==''){this[o.reqMethod]()}; 
     };
    
       //-- method desc
       varName.prototype.publicMethodName = function(){
    
         gen.CheckEmailAddress(newEmail);
     
       }
     
       //-- method desc
       varName.prototype.publicMethodNameTwo = function(){
         //-- call to my private method
         APrivateMethod();
       }
      
       function APrivateMethod(){
         //-- private stuff done here
     
       }
     
       window.varName = varName;
    
    }(window));
    
    
    
    
    
     /********
      *
      * Generic JS File
      * File saved as: GenericJS.js
      *
      *******/
    
    ;(function(window){
        "use strict";
        var GenericJS = function(methodName){
    
        this.data = {}
    
        this.init();
     };
     //
        var o, gen;
    
        varName.prototype.init = function(){
    
        o = this.data;
    
        };
    
        GenericJS.prototype.CheckEmailAddress = function(){return _checkEmail(email);}
        GenericJS.prototype.GenericPublicMethodTwo = function(){return _AnotherPrivateMethod();}
     
      
        function _checkEmail(em){
        // do stuff here
        }
    
        function _AnotherPrivateMethod(){
        // do stuff here
        }
     
        window.GenericJS = GenericJS;
    
    }(window))
    
    
    
    /*--- USE
    
    //-- include -- path/to/GenericJS.js
    //-- include -- path/to/CustomJS.js
    //--script tag ((typeof varName) !== 'undefined') ? new varName("publicMethodName") : null;
    
    
     By sending the method name within the set up 'new varName("publicMethodName")' then i can use CustomJS.js for all my site pages and simply call the page method:
     eg: new varName("homeDetails"); for say index.php or new varName("signup"); for the signup.php page, or if each page has its own file HomePage.js then I would not be required
     to call it in this way but would call it within the main init method: EG: new varName() then in the HomePage.js init method i would do all the work there and the if(o.reqMethod!==''){this[o.reqMethod]()}; is not required.
    
    */
    
    
  24. Chris, I give you an “A” for effort, and a “B-” for execution.

    As others have pointed out, the “s” variable will be global, and thus runs the risk of being trampled by other modules. It’s also not a true module pattern. Assuming you want it to be a singleton, you could modify your example slightly to this (which is similar to some of the other posts in the comments):

    
    var NewsWidget = (function () {
        var s; // private alias to settings
        
        return {
            settings: {
                numArticles: 5,
                articleList: $("#article-list"),
                moreButton: $("#more-button")
            },
    
            init: function() {
                s = this.settings;
                this.bindUIActions();
            },
    
            bindUIActions: function() {
                s.moreButton.on("click", function() {
                    NewsWidget.getMoreArticles(s.numArticles);
                });
            },
    
            getMoreArticles: function(numToGet) {
                // $.ajax or something
                // using numToGet as param
            }
    
        };
    })();
    
    • Permalink to comment#

      I think as long as he wraps the entire thing in a self-executing anonymous function, then there’s no concern about the global “s”. And that would be similar to your proposal above (which I like BTW).

    • Matt
      Permalink to comment#

      Excellent, Peter. Clean, and works well. I will follow this pattern myself with future code!

    • If the entire thing is wrapped in a self executing anonymous function, then “s” would not be global, but then neither would NewsWidget, meaning he couldn’t call NewsWidget.init() outside of the self executing function. The work around would be to declare NewsWidget without “var” which would implicitly create it as a global, but I would generally discourage that.

      Instead of wrapping the entire thing in a self executing anonymous function, I’ve basically kept the anonymous function but have it returning an object (and then I assign that to NewsWidget). It’s similar, but this subtle change makes a big difference.

    • Permalink to comment#

      I guess the way I’m looking at it is that this would be the structure for the entire JS for a single site/app. Therefore, it wouldn’t matter that “s” is global to the application, or that the main object is not accessible outside the function. Especially if it’s a small app that isn’t going to have any potential conflicts and whatnot.

    • Jerry Batorski
      Permalink to comment#

      I like this because it fixes the settings variable being global, but how would I use this with the module pattern using closures to make functions private/public (encapsulation). If every function is in the return, it will be public. If you move functions out of the return, you’ll make them private but lose access to the settings var.

    • @Jerry, If you move functions out of the return, you’ll make them private. You’ll still have access to the settings via the private “s” variable. For example:

      
      var NewsWidget = (function () {
          var s; // private alias to settings
          function somePrivateFunction() {
              alert("There are " + s.NumArticles + " articles");
          }
      
          return {
              settings: {
                  numArticles: 5,
                  articleList: $("#article-list"),
                  moreButton: $("#more-button")
              },
      
              init: function() {
                  s = this.settings;
                  this.bindUIActions();
                  somePrivateFunction();
              },
      
              bindUIActions: function() {
                  s.moreButton.on("click", function() {
                      NewsWidget.getMoreArticles(s.numArticles);
                  });
              },
      
              getMoreArticles: function(numToGet) {
                  // $.ajax or something
                  // using numToGet as param
              }
      
          };
      })();
      

      In that example, I’ve added a private method, “somePrivateFunction”, which has access to the settings via the private variable “s”. Alternatively, I could have done something like take a reference to “this” as one of the parameters:

      
      function somePrivateFunction(o) {
          alert("There are " + o.settings.numArticles + " articles");
      }
      

      And then where I call the private function:

      
      init: function() {
          ...
          somePrivateFunction(this);
      }
      
    • Permalink to comment#

      Very nice Peter. I am currently experimenting with this modular pattern also!

    • Permalink to comment#

      Another way to achieve this is.

      (function (NameSpace) {
          var s, // private alias to settings
              api = NameSpace.NewsWidget;
      
          api.settings: {
              numArticles: 5,
              articleList: $("#article-list"),
              moreButton: $("#more-button")
          };
      
          api.init: function() {
              s = api.settings;
              api.bindUIActions();
          };
      
          api.bindUIActions: function() {
              s.moreButton.on("click", function() {
                  api.getMoreArticles(s.numArticles);
              });
          };
      
          api.getMoreArticles: function(numToGet) {
              // $.ajax or something
              // using numToGet as param
          };
      })(NameSpace);
      
  25. Great article! I have worked with codes following those patterns, but I had some doubts. Thanks.

  26. Permalink to comment#

    Great explanation, man. Happy to read it :)

  27. Permalink to comment#

    Great bit of explanation to write scripts based on patterns. Much needed guidelines to avoid any errors while writing a script.

  28. Félix
    Permalink to comment#

    Hi, I think you meant Addy Osmani !
    Great article !
    Cheers

  29. Good read, I also agree with comments made by Peter Foti above. I think you would fall in love with Sparky.js if you took a look – http://sparkyjs.com/

  30. I’m not a pro at JS, but my javascript “a ha” moment came with the revealing module pattern:

    http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

    I agree with the author that it’s an improvement. I had done a little bit of OOP (such as it is) in PHP so having an object with public and private methods clicked for me.

  31. Great little article about the module pattern! I’ve really been getting into it lately, with the Rails asset pipeline and trying to organise our mess of JavaScript at work using require.js. It makes everything much neater IMO, and I love having files with just a couple of hundred lines of JS rather than a couple of thousand.

  32. Permalink to comment#

    Thanks Chris …

  33. Honestly, you just scratched the surface of closure logics. It took me some time to get behind those secrets, but once understood the whole closure subject reveils the pros of JS programming.

    Just expand the term “module” and think in terms of “frameworks”. Build your own libraries and use them consistently.

    One example:
    You use a variable outside of your module. How nice would it be to utilize pure “private” variables, only accessible from inside the module?
    The master science is to keep a reference inside the module which points to itself in any context. No ,”this” doesn’t help since it points to other objects when a module function is called from an event handler or a timer.

    There are a lot of docs and examples around, and I can only encourage everyone to increase their knowledge – Its’s worth it, and it will turn your ACME Javascript into a versatile programming language.

  34. Justin Lowery
    Permalink to comment#

    From what I understand about patterns, this is not a Module pattern, but a simple Singleton pattern. Singletons are defined by their simple construction via the object literal syntax. They commonly lack encapsulation as everything (properties and methods) is usually exposed and accessible publicly.

    Because of this “everything is exposed” it opens the object up to mutation. In multiple dev environments or public API’s this is usually not good form and encapsulation is more desirable.

    Encapsulation, what a singleton usually lacks, is what provides a controlled API where you only expose privileged methods that have access to the private variables. This prevents accidental overwriting and mutation.

    Modules on the other hand, are built with the purpose of providing encapsulation. The basic Module is a function that returns a privileged function or an object with privileged methods that have access to private variables, but the catch is these variables that contain the data are not a part of the retuned object, so they are not exposed publicly, outside of the module function.

    If you’re thinking, “that sounds like a closure”, it is! This closure allows the developer to control what and how the data is accessed, e.g. encapsulation. This is best form for public API’s and multiple development teams.

    TL;DR

    Singletons are defined by an object literal syntax and don’t normally have encapsulation with private and privileged entities:

        var mySingleton = {
    
            name: 'Justin',  // I'm public.
    
            getName: function () {  // I'm public too!
    
                return name;
            }
        }
    

    Modules on the other hand are defined by a function returning an object with privileged methods having access to private variables:

        var myModule = function () {
    
            var name = 'Justin',  // I am private!
                obj = {};  // I will be exposed!
    
            obj.getName = function () {
                
                return name;
            };
            obj.setName = function (newName) {
    
                name = newName;
            };
    
            return obj;
        };
    

    At least, this is how I understand patterns in JavaScript. Let me know if I’m misunderstanding something here.

  35. Rick Blalock
    Permalink to comment#

    I was going to jump in and mention that this isn’t really a module pattern but a singleton but Justin Lowry beat me to it. I don’t like to get religious on patterns and programming techniques because a lot of times it’s just semantics or differences in background. There can be singleton modules, instantiable modules, modules that have factories inside, etc.

    In this case, the code samples are def. singletons. There’s nothing wrong with singletons but for those not paying attention to what is going on…it could cause memory leaks if you’re not manually managing what the object is referencing.

  36. Permalink to comment#

    Till the middle of comments list I was afraid nobody would have mentioned the AMD (Asynchronous Module Definition).

    Of course, the Singleton pattern shown in the article usually would fit needs of the most developers. But a bit more complex web-apps consisting of many sub-modules with various dependencies are pain in the a…

    I’ve come from PHP World into the JavaScript-driven apps and some things went out quite weird. But when I started learning the AMD-approach, developing an app started to enjoy me due to whole process.

    Somebody wrote earlier about private variables. Huh, there’s some problems indeed. I solved that situation using build scripts which analyze content of my source code, for example this._somePrivateStuff() is being rewritten to simple var _somePrivateStuff() and further parsed. Why so weird? Huh, I’ve been googling and reading many docs about TDD in JS and one thing was sad – absolutely no reflection mechanisms at all. So that – in development version you should make your private/protected variables… public but prefixed and just before release – replace declarations with proper modifiers.

    If someone has better experience for designing such modules regarding the TDD approach, feel free to respond on this comment.

    • I’m not sure how deep your knowledge of JS goes, but privacy can only be created by using function scope to close over the variables (i.e. closure), hiding them from the outside scope. Prefixing variables with the underscore does absolutely nothing functionally.

      If you’re developing a complex JS app, and you are wanting to test it, the best way is to use an actual Module or Factory pattern and have it return the methods you desire without returning the private variables. Then, you can have the testing framework test the API and ensure that it returns what’s expected.

      One of the best JS frameworks that has gorgeous built in unit testing is AngularJS. They’ve built the whole framework with testing in mind. I highly recommend looking into it and discovering how they went about solving problems.

      They’ve even create dependency injection (DI) that makes testing nearly effortless. DI is rarely found but a very powerful way of handling dependencies.

      Anyway, if you desire true privacy, you can’t use what you know about other “classical” languages, and you have to really understand the prototypal nature of JS and its lexical scoping. If you try to impose more classical styles to JS, you’ll get bitten in the end.

    • Permalink to comment#

      Uhm, my bad – of course those variables are enclosed by closure. I meant accessing the private fields inside during testing because – AFAIK – no JS VM has something like reflection abilities.

      I’ll look at AngularJS, thx for feedback.

  37. As others have stated this is actually not The Module Pattern, it’s the Singleton (Object Literal Pattern). Rebecca Murphey has a really great post about this pattern in case anyone wants to learn more about it : http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/

  38. Awesome stuff, thanks Chris.

  39. Permalink to comment#

    Amazing explanation on module pattern design now only if we had a 20 page book that focus on module design pattern and different approaches. Andy Osami books are great but he explains all the patterns and Module pattern is the most popular.

  40. vishal
    Permalink to comment#

    i wanted to ask if i subscribe to lodge,can i learn server side techniques like automatically adding up new feeds on the home page just like this site’s homepage and how to handle forums n all ??? i am a beginner in all this stuff(confused).

  41. Love this pattern and have been using a flavor of it for awhile now.

    Quick tip: In the bind_events method, .on() has the ability to pass in event.data. This means that you don’t necessarily need to wrap a function call inside of another function just to pass arguments.

    A snippet from one of my bind_events methods.

    ...
            bind_events: function() {
                this.$the_window.on('resize', App.resize_img);
                this.$the_window.on('resize', App.recenter_carousel);
                this.$the_window.on('popstate', App.handle_state);
                this.$doc.on('swiped_left', { index: 1 }, this.swap_studio);
                this.$doc.on('swiped_right', { index: -1 }, this.swap_studio);
                this.$doc.on('click touchend', '.control.next, .pad.right', { index: 1 }, this.swap_studio);
                this.$doc.on('click touchend', '.control.prev, .pad.left', { index: -1 }, this.swap_studio);
                this.$doc.on('click touchend', '.artist-list a',{ type: 'list-link', index: $(this).data('index') }, this.swap_studio);
                this.$doc.on('click', '.btn-list, .controls .index', this.toggle_list);
                this.$doc.on('click touchend', '.btn.toggle-box, .artist-name', this.toggle_box);
            },
    ....
    

    Notice the JSON object parameter in some of these bindings. { index: 1 } can later be accessed inside of the said function via something like…

    If (event.data.index === 1) {
        // do some cool stuff
    }
    

    Better? Not necessarily. Just another tool in the belt.

    • Brendan
      Permalink to comment#

      The event.data tip is very cool. I use .on() constantly and never knew this trick. Very cool. Thanks for sharing.

    • This is a cool pattern, but I’d only use this for passing objects that have been generated on the fly. If you just want to execute a method on an object as a callback, personally I prefer using $.proxy.

      e.g. using Chris’ code above:

      
      bindUIActions: function() {
          //$.proxy binds a function to an object, 
          //so getMoreArticles always runs in the context of the widget
          this.settings.moreButton.on("click",$.proxy(NewsWidget.getMoreArticles, NewsWidget));
      },
      
      getMoreArticles : function() {
          //no need for param, can now access settings as you'd expect
          console.log(this.settings.numArticles);
      }
      

      Saves us needing the extra s var

  42. Permalink to comment#

    Hi, I’ve slipped a bit in previous code samples – in my example of single instance “this” point to “window” object. Here’s updated version:

    /**
     * @name someFunction
     * @author 
     *
     * Basic usage:
     * someFunction.init();
     *
     * additionally you can use methods like someFunction.methodName();
     */
    var someFunction = new(function () {
        //assign _root and config private variables
        var _root = this;
        var _cfg = {
            "someOption": "some value"
        }
    
        /*
            INITIALIZE
        */
        this.init = function () {
            //some code
            _somePrivateMethod();
            _root.somePublicMethod();
        }
        /*
            Some Private Method (no "this")
        */
        var _somePrivateMethod = function () {
            //some code
            console.log("_somePrivateMethod");
        }
        /*
            Some Public Method
        */
        this.somePublicMethod = function () {
            //some code
            console.log("somePublicMethod");
        }
    
    })();
    
    //declaration and initialization of someFunction
    someFunction.init();
    
    //someFunction._somePrivateMethod();
    //returns: TypeError: someFunction._somePrivateMethod is not a function
    
    //someFunction.somePublicMethod();
    //returns: "somePublicMethod"

    jsFiddle code:
    * http://jsfiddle.net/nightman/ynUZf/ – single instance, basic example
    * http://jsfiddle.net/nightman/3kzhj/ – single instance, example with additional options
    * http://jsfiddle.net/nightman/TBKvB/1/ – multiple instances (constructor example)
    * http://jsfiddle.net/nightman/prpU2/2/ – multiple instances (constructor example) with auto init

    Regards.

  43. Be careful. There are many people that write about JavaScript, that are not experts (not talking about you, but who we get our information from). I’d bet there are more novice programmers churning out JavaScript than any other language, leading to a proliferation of plug and pray widgets and libraries.

    Programming is not just about learning the syntax of a language and forging ahead, that’s experimentation (nothing wrong with that, just don’t use it as an example of the best way to do it). Programming is also not just about communicating with a computer, or learning algorithms and patterns. What’s also important, especially these days, is that it is about communication with humans, and showing a fellow developer what your program does (even yourself, especially once your memory has lost its mental model of your program).

    There are many JavaScript ‘best practice’ articles and coding standards that focus on writing for the compiler, not the author. Programming itself (in the abstract sense I suppose) is a skill which is very difficult to transfer to others, learning syntax, algorithms and patterns is the easy part.

    Bret Victor touches on this, and a lot more in his wonderful essay: http://worrydream.com/#!/LearnableProgramming if you have the time to read it, it’s rather long, but an absolute joy.

    A good module would not allow that settings object to be manipulated directly from outside the module, they would be private to the module, and only be modifiable from outside if a public function existed to allow it. That way, it can be validated, what if somebody did s.numArticles = document.location.search.substring(1)?

    A great module would not just have programmatic access to settings, there would be a way to retrieve all the parameters it needs from the document. You shouldn’t be writing JavaScript modules for JavaScript programmers, you should be writing for HTML authors, especially if you want more people to use them, they just want to write the HTML to include your script and for that to be the end of the matter.

    On top of this, an awesome module would not have any HTML IDs hardcoded, anywhere. It would inspect the document and discover whether itself was required and act accordingly, pretty much like how polyfills work, using elements, classes, microdata, anything but HTML IDs.

    Your ‘module’ is a merely an object created using the object literal syntax. The reason you need to export your reference to settings is that you haven’t actually used the module pattern from that book: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript – the book starts the module pattern by describing the object literal syntax as a prerequisite, then goes on to describe the module pattern itself. The object literal is a way of creating an object without using new Object() like the string literal creates a string without using new String().

    That book looks pretty good. At least it knows uses the correct terminology for Immediately Invoked Functions, unlike quite a few of the previous comments, who are still calling them self-executing. This function is self-executing:

    function selfExecute()
    {
      ... //do stuff
      selfExecute() ; // call myself, hopefully not infinitely, like this!
    }

    Self Executing functions belong to discussions about recursion. This function is invoked immediately:

    var MyModule = function()
    {
      ... // do stuff
    
      return {
        // public interface is returned here.
      };
    }();

    Although I prefer to use the new keyword personally:

    
      var MyModule = new function()
      {
        ... // do stuff;
    
        // public interface is declared here.
        this.publicFunction = privateFunction;
      };
    

    No trailing parenthesis are required, and you don’t have to return the module’s interface, just use the new object (this) to define it.

    Why you have NewsWidget.init(); SomeOtherModule.init(); within an Immediately Invoked Function Expression, I’ll never know. Since you have nothing in there to protect or make private. Still, if the modules themselves were invoked immediately, then you wouldn’t need to call init on them at all.

  44. I took this and extended it with options. Thanks to @karol with the example from his method.
    CodePen: Module Pattern with options object

    var s,
    NewsWidget = {
    
      settings: {
        numArticles: 5,
        articleList: $("#article-list"),
        moreButton: $("#more-button")
      },
    
      init: function(options) {
        this.settings = $.extend(this.settings, options);
        s = this.settings;
        this.bindUIActions();
      },
    
      bindUIActions: function() {
        s.moreButton.on("click", function() {
          NewsWidget.getMoreArticles(s.numArticles);
        });
      },
    
      getMoreArticles: function(numToGet) {
        // $.ajax or something
        // using numToGet as param
      }
    
    };
    
    $(function(){
      NewsWidget.init({
        numArticles: 6
      });
    
      console.log(s.numArticles);
    });
    
  45. Ryan
    Permalink to comment#

    s.moreButton.on click event never get triggered, does anyone tell me why?
    if I use $(“#more-button”) instead, it will work

  46. Permalink to comment#

    I’ve just recently begun to use a modification of this pattern. I like using objects this way, but I don’t like how hard it gets to make sense of sub-objects as code gets more and more complex. I also feel fairly strongly about using full words as variable names in any case where it’s possible. I find that it’s much more self-documenting. My code ends up looking more like this:

    
    
    var myApplication = myApplication || {};
    
    (function() {
    
    myApplication.smartModal = myApplication.smartModal || {};
    myApplication.smartModal.modal = myApplication.smartModal.modal || {};
    myApplication.smartModal.url = myApplication.smartModal.url || {};
    
    myApplication.smartModal.initalize =  function () {
      // Centralizes all of the starting calls to kick this thing off 
      myApplication.smartModal.events() 
    }
    
    myApplication.smartModal.settings = {
      // some settings as an object
    }
    
    myApplication.smartModal.events = function () {
      // event bindings
    }
    
    // Things that deal with modal states
    
    myApplication.smartModal.modal.open = function() {
      //code that opens the modal with ajax
    }
    
    myApplication.smartModal.modal.close = function() {
      //code that closes the modal
    }
    
    myApplication.smartModal.modal.changeContent = function() {
      //changes the content in the modal via ajax
    }
    
    // Things that deal with URL states
    
    myApplication.smartModal.url.change = function(url) {
      // changes the URL using HTML5 history API
    }
    
    myApplication.smartModal.url.onChange = function () {
      // Does something when the url changes
    }
    
    myApplication.smartModal.url.getVariables = function (url) {
      // Returns the GET variables from a given URL as an object
    }
    
    
    }) ();
    
    $(function() {
      myApplication.smartModal.initalize();
    })
    
    
    

    I guess I could also start using the “settings” portion as default settings, and then passing in a “settings” object to the initialize function to overwrite select defaults. I’m sure there are lots of other things that could be better, but this is the way my pattern is right now. I like that even though I’m working with an object, I don’t have to wonder as much about where sub objects end, and if they’re commented right.

  47. Ian
    Permalink to comment#

    I love this style of coding in your example. It’s much cleaner to me. But looking at the other styles in the comments got me looking at a small fullscreen module I wrote a couple days ago and I realized every method in the module is public. I would love to stick with this style if it is possible to make methods private.

    So I suppose the way others have done it is better. I was wondering one thing though. Is it necessary or good practice to pass in window in a self invoking function like this example? I know jquery plugins do it in case ‘$’ gets overwritten by another script but will ‘window’ ever get overwritten?

    
    ;(function($, window){
        var NewsWidget = function(args) {
            
            this.init =  function() {
                this.args = args || {};
                _privateMethod();
            }
    
            var _privateMethod = function() {
                console.log('hello from private method with some args: ' + JSON.stringify(this.args));
            }
    
            this.init();
        }  
    
        window.NewsWidget = NewsWidget;
    })(jQuery, window);
    
  48. Ian
    Permalink to comment#

    Makes more sense to me after reading more of the comments and finding this link from Oriely. The part about modules with constructors also answers another question I had about how to pass options into a module.
    How to use the module pattern

  49. Scribblerockerz
    Permalink to comment#

    Nice article, there is just one thing what I would change…
    var s;

    You should declare the “s” variable inside the private scope of init, cause you create a global s variable with “undefined”. It’s always better to keep global variables to a minimum.

  50. Permalink to comment#

    Nice article!

    I have been using a closure that Christian Heilmann talks about in his article, Seven JavaScript Things I Wish I Knew Much Earlier In My Career, called “the revealing module pattern” and found it to be working well. I was actually thinking about closure in your very first code snippet of this article and I haven’t tried using an object for closure. I guess everyone have their own style but which way is generally the best?

  51. Jack
    Permalink to comment#

    You should give a look at
    Terrific JS

  52. Nice article. I have been writing Javascript apps for a while and have been frustrated with how difficult it is to structure apps. I ended up making my own Javascript app structuring program called structureJS https://github.com/ShamariFeaster/structureJS

  53. More module approach is your using clean JS

    var NewsWidget = {
    
    defaults : {
        settings1 : true,
        settings2 : 'some value'
    },
    
    
    init : function( obj ){
        if(obj.length &gt; 0) 
            this.combine(obj);
    
    },
    
        someFunction function() {
                // blabla
        },
    
    /** 
     * Combine settings with
     * passed params
     */
    combine : function( obj ){
    
        for( k in obj ){
            var key = k;
            for( s in this.defaults ) {
                if(s === key) {
                    this.defaults[s] = obj[key];
                }
            }
        }
    
    }
    

    }

    ;(function(){

    // Not needed
    // NewsWidget.settings.crosshair = true;
    
    NewsWidget.init({
        settings1  : 'this will override settins1, leaving settings2 at default'
    });
    

    })();

  54. Matt
    Permalink to comment#

    This does not appear to be an actual example of Module Pattern design? You are simply assigning an object literal to a variable… Module Pattern must use an anonymous function that executes inline to create a closure on the namespace you are creating. This allows for public/private members which mimics OOP

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".