Brian Cray ··· Home > Blog > Javascript > Javascript module pattern: When to use it and why

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