1

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.

Dizip
  • 85
  • 7

1 Answers1

1

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).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So... they're the same thing? – Sheraff Jan 03 '20 at 11:08
  • @Sheraff — No, they are not. – Quentin Jan 03 '20 at 11:09
  • In both cases, `MyModule.method = () => console.log('hello')` will make `.test` log `"hello"` – Sheraff Jan 03 '20 at 11:12
  • 1
    @Sheraff — I said that in the answer. I also said that `MyModule = {}` will have different results. – Quentin Jan 03 '20 at 11:12
  • Oh I didn't think this through, did I! Maybe to make your answer clearer (because it wasn't obvious to me the first time I read it), you could says that one holds *a reference to the object* while the other *directly calls the object through the variable name*, meaning that if we reassign the variable to something else, one still has the reference to the original and the other does not. – Sheraff Jan 03 '20 at 11:18
  • @Sheraff — Both use variable names. Both variables hold references to an object. So that would be wrong. The only difference is the scope of the variables … one of which I called out as being a global in the answer. – Quentin Jan 03 '20 at 11:19
  • @Quentin If I understand correctly, the second approach is better for security reasons. I've created a small [jsbin](https://jsbin.com/qawuremeta/edit?js,console). Is that good example or should I consider something more? – Dizip Jan 03 '20 at 11:19