What is the functional difference between these two module template syntaxes

I see this syntax everywhere:

var mod = (function(){ var pvtvar; var pvtfunc = function(){}; //return an object literal return { pubvar : 'whatever', pubfunc : function(){} }; }()); 

I recently met this syntax:

 //first create empty object var mod = {}; (function(mod){ var pvtvar; var pvtfunc = function(){}; //modify the mod object argument mod.pubvar = 'whatever'; mod.pubfunc = function(){}; }(mod)); //pass object to IIFE 

I know that they both work, and I think I fully understand why I just want to make sure that I don’t miss anything ... Given the same members, you get the same objects, this is just that in the second example, the mod refers to an empty object in the global scope for a split second, whereas in the first example, mod only ever refers to a complete object when its value is returned by IIFE.

So, do I correctly believe that the only difference is the (very small) amount of time during which the second object lives as an empty object? And, my next question is: do you use the second syntax and why?

+1
javascript design-patterns iife
Jul 27 '14 at 3:59
source share
1 answer

You're right. In your example, the first syntax is cleaner and more readable.

You use the second syntax when you want to transfer something more than an empty object to the module and get an extended object in return.

+1
Jul 27 '14 at 4:06
source share



All Articles