这两种不同的模块模式语法之间的功能区别是什么? [英] What is the functional difference between these two different Module pattern syntaxes

查看:128
本文介绍了这两种不同的模块模式语法之间的功能区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个句法:

var mod = (function(){
  var pvtvar;
  var pvtfunc = function(){};

  //return an object literal
  return {
    pubvar : 'whatever',
    pubfunc : function(){}
  };
}());

我最近遇到这种语法:

//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

我知道他们都工作,而我认为<我完全理解为什么,我只是想确保我没有丢失任何东西...给定相同的成员你最终得到相同的对象,这只是在第二个例子中 mod 在全局范围内引用一个空的对象一秒钟的时间,而在第一个例子中, mod 只有当一个值被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?

推荐答案

你是对的。在您的示例中,第一种语法更清晰,可读性更高。

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.

这篇关于这两种不同的模块模式语法之间的功能区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆