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

不羁的心 提交于 2019-12-11 05:53:37

问题


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?


回答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.



来源:https://stackoverflow.com/questions/24977784/what-is-the-functional-difference-between-these-two-different-module-pattern-syn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!