Learning the JS Module Pattern.
I am trying to figure out the differences between an IIFE and a regular function in this use case. It looks like the ONLY advantage of an IIFE is that my module becomes an object (since the IIFE returns immediately) so I don't need to use the call invocation/param ()
syntax on my module.
Is there any additional benefit? Consider the following code:
//IIFE
var HelloWorldEncapsulated = (function(){
return {
privateMethodEncapsulated: function () {
console.log('ayy lmao encapsulated');
}
}
})();
HelloWorldEncapsulated.privateMethodEncapsulated();
//Just a function
var HelloWorld= function(){
return {
privateMethod: function () {
console.log('ayy lmao');
}
}
};
HelloWorld().privateMethod();
Again, is there any difference between the two besides using ()
and not using it? It seems that privateMethod
is just as hidden in the non-IIFE function as it is in the IIFE. Code here in case you don't want to type 2 words
The only difference in those is when you're executing your function. In your second example, if you want to call another method (or call privateMethod
more than once), you'd have to execute it again (not ideal):
HelloWorld().privateMethod();
HelloWorld().privateMethod(); // Calls HelloWorld a second time, creating a
// whole new object to make the call on (bad idea)
...or remember the result of the first execution an dreuse it:
var hw = HelloWorld();
hw.privateMethod();
hw.privateMethod();
...at which point you're back to your first example.