What is the functional difference between these two different Module pattern syntaxes
Asked Answered
D

1

1

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?

Dumbarton answered 27/7, 2014 at 3:59 Comment(0)
A
1

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

You use the second syntax when you want to pass along something more than an empty object into the module and get an augmented object in return.

Anderton answered 27/7, 2014 at 4:6 Comment(1)
I see, that seems obvious...now that you've written it. So you could use the second syntax to build a module that inherits from another. What's strange though is that I've so far only ever seen it used with an empty object.Dumbarton

© 2022 - 2024 — McMap. All rights reserved.