Best way to use Module Pattern in javascript

3

I'm working on a project and using the Module Pattern pattern in the javascript itself. But during the implementation of the project I had some doubts.

1st Doubt:

Is there any difference between the two ways "Immediately-Invoked Function Expression (IIFE) "

var modulo = (function() {
   //codigo
}());

var modulo = (function() {
   //codigo
})();

Ben Alman, author of the article: Immediately-Invoked Function Expression (IIFE) implements the first form.

Ja Addy Osmani, author of the book: Learning JavaScript Design Patterns implements the second form.

I wonder if there is any kind of technical difference between these two forms. Or are they just two different ways to do the same thing?

2nd Doubt:

I thought it would be interesting to add sub modules within my main module. But I looked in several examples and links related to the subject and found no approach using sub modules. So I was in doubt, whether or not I should do this. Can using sub modules cause me future problems or pollute my code?

    
asked by anonymous 02.09.2016 / 21:25

1 answer

4

Regarding your first question: both are equivalent, it's a matter of preference:

(function () { … })(); <-- a melhor (ver edit em baixo)
(function () { … }());

Edit:

I got into the chat in SOen JavaScript and Reddit and rightly mentioned that with the syntax of flexa functions, the second syntax does not work (!). Which makes perfect sense.

Example:

(function (nr) { console.log(nr);})(1);
(function (nr) { console.log(nr);}(2));
(nr => console.log(nr))(3);
(nr => console.log(nr)(4));

o 4 never appears ...

jsFiddle: link

Regarding your second question: use IIFEs to limit scope whenever you want. The reason why one does not use much "submodules" is because the module concept (or best practices) is to make each module as simple and re-usable as possible. So a module should never be so large that it needs submodules. But there's no harm in creating them.

Now, aside from that, I think you should look at the Common JS modules, or better yet, new syntax coming here with 'import. This allows you to separate modules into files and with a compiler such as Babel, Webpack or Browserify you can convert this into "old" JavaScript and run it in the browser ...

    
02.09.2016 / 21:49