javascriptecmascript-5revealing-module-pattern

ES5 Module pattern usage


Could you explain to me what is the difference between that two approaches (FirstModule and SecondModule:

var MyModule = (function () {
    return {
        method: function () {
            console.log("MyModule:method");
        }
    }
})();

var FirstModule = (function () {
    return {
        test: function () {
            MyModule.method();
        }
    }
})();

var SecondModule = (function (myMethod) {
    return {
        test: function () {
            myMethod.method(); 
        }
    }
})(MyModule);

In both cases we have the same object, it isn't a copy. I would be grateful for any good information, advantages, disadvantages of any approach.


Solution

  • The first approach uses the MyModule variable, which can be overwritten by other code, outside the module, after the FirstModule value has been asigned.

    The second uses the myMethod variable, which can't (although properties of the object assigned to myMethod still can because that object is still globally available via the MyModule variable).