I see this syntax everywhere:
var mod = (function(){
var pvtvar;
var pvtfunc = function(){};
//return an object literal
return {
pubvar : 'whatever',
pubfunc : function(){}
};
}());
I recently came across 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 understand completely why, I just want to make sure I'm not missing anything...Given identical members you end up with identical objects, it's just that in the second example mod
references an empty object within the global scope for a fraction of a second, while in the first example mod
only ever references the complete object once its value is returned by the IIFE.
So, am I correct in thinking that the only difference is the (very small) amount of time that the second object lives as an empty object? And, my follow up question: do you use the second syntax, and why?