javascriptmodulemodule-pattern

Javascript module pattern and empty objects


When using the Module pattern to extend a module we do something like this:

var NewModule = (function (Main) {

    Main.extension = function () {};
    return Main;

})(Main || {});

That works great and the question is, if Main is not declared we avoid errors by passing an empty object Main || {}. How do we prevent this dependency from breaking? Granted, we wont have any errors at first but if we are not able to attach our extension to Main we will encounter other type of errors.


Solution

  • If the goal is to extend Main, you usually wouldn't assign to NewModule. You'd rather do

    // a.js
    var Main = (function (localMain) {
        localMain.extensionA = function () {};
        return localMain;
    })(Main || {});
    

    We do this so that we can have multiple modules like that:

    // b.js
    var Main = (function (localMain) {
        localMain.extensionB = function () {};
        return localMain;
    })(Main || {});
    

    All of them will either create or extend the Main object, so that it doesn't matter in which order they load - both a.js, b.js and b.js, a.js will work. The pattern is also sometimes simplified to

    (function (localMain) {
        localMain.extension = function () {};
    })(Main = Main || {});
    

    (although that lacks the var declaration).

    If your module (especially your newModule) does have an actual dependency on the main module, and requires that it was loaded before it is executed, you would not use this defaulting pattern.