Javascript module pattern: When to use it and why


There have been a few criticisms of the javascript module pattern, despite its many advantages. Take for example Jonathon Snook’s “Why I don’t like javascript’s module pattern”. While everyone has their own style, my fear is that people, given Snook’s demanding presence, will take his word for gospel without understanding it.

This article isn’t about teaching you the pattern, but more about when to use it and why—though I’ll start with a brief example of the pattern to get us all on the same page.

A brief example in my favored flavor

var module = (function () {
    // private variables and functions
    var foo = 'bar';

    // constructor
    var module = function () {
    };

    // prototype
    module.prototype = {
        constructor: module,
        something: function () {
        }
    };

    // return module
    return module;
})();

var my_module = new module();

This appears to be a lot of unnecessary code at first glance, but each line is plays a key role in making the module pattern advantageous.

The when & why

    • Scalable. Modules are isolated pieces of code that when well designed, work independently of other modules and therefore can be removed and added as necessary.
    • Team-ready. Building a large-scale javascript application is simpler with the module pattern. Each developer on a team can be assigned a set of modules to develop and can work in parallel with minimal conflicts. Additionally, everyone can write in their own preferred style within the context of the pattern without preferences getting in the way of progress.
    • Localized. Anonymous wrappers automatically create a new “namespace” for the whole module. This has performance advantages in garbage collection and scope chain walking. Furthermore, variables can be passed into the anonymous wrapper to localize commonly accessed global variables, such as windowdocument, and jQuery, like so:
      var module = (function (window, document, $) {
          // module stuff
      })(window, document, jQuery);
    • Cross-instantiation private variables. Normally when you instantiate an object with something likenew module(), a whole new clean object is created–and that’s still the case. But the private variables will retain their values across instantiations.
    • Extensible. Want to dynamically add additional methods to a module? No problem.
      // extend it with something_else();
      var module = (function (module) {
          module.prototype.something_else = function () {
          };
          return module;
      })(module);

      With a few changes this same pattern can be used to “subclass” an existing module.

    • Deferrable. Another advantage of its isolation and containment is that you can inject it on demand without worrying about its impact on other modules. Using the following code, for example:
      function inject_module (module_file) {
          var h = document.getElementsByTagName('head')[0];
          var s = document.createElement('script');
          s.type = 'text/javascript';
          s.src = module_file;
          h.appendChild(s);
      };

Bonus: Tips for well-designed modules

      • Don’t make modules explicitly depend on each other. Everything each module needs to work should be confined into either the module or plugins that are shared among modules.
      • Have modules communicate to each other through event subscriptions, not through direct calls to each other. They call this a pubsub. If you’re using jQuery, check out jQuery Tiny Pub/Sub. If not,here’s a good vanilla pubsub.
      • Create a light integration layer that handles module injection and interaction.

Conclusion

The javascript module pattern has many benefits through isolation and localization. They shouldn’t be written off until you’ve given due thought into the design of your application and your team. 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.

Copy from http://briancray.com/posts/javascript-module-pattern

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s