(function() {...}()); 之间有区别吗?和 (函数() {...})();?
可能的重复:
自动执行匿名 JavaScript 函数的括号位置?
有时我看到:
(function() { ... }());
有时我看到:
(function() { ... })();
我看到带参数和不带参数的两种形式。他们两者 两者 net/WZ3X2/" rel="nofollow noreferrer">执行匿名函数。
两种形式有区别吗?是否有任何令人信服的理由来使用一种形式而不是另一种形式?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这两种形式没有实际区别,但从语法的角度来看,两者之间的区别在于分组运算符 - 括号 - 将在第一个示例中保存
CallExpression
,其中包括FunctionExpression
:在第二个示例中,我们首先有一个完整的
CallExpression
,其中包含FunctionExpression
:There is no practical difference in those two forms, but from a grammatical point of view the difference between the two is that The Grouping Operator - the parentheses - will hold in the first example a
CallExpression
, that includes theFunctionExpression
:In the second example, we have first a whole
CallExpression
, that holds theFunctionExpression
:就编译器而言,两者之间没有区别。不过,会发现 Douglas Crockford 的 JavaScript (function () {}()) 样式“nofollow">代码约定。
There is no difference between the two, so far as the compiler is concerned. However, will find that the
(function () {}())
style is recommended in Douglas Crockford’s JavaScript code conventions.就差异而言,它实际上只是语法糖。有点相当于:“你喜欢 jQuery() 还是 $()?”两者都可以编译、执行和互换使用(AFAIK)。
从迄今为止我看到的代码示例来看,似乎有更多的人遵循 Crockford 代码约定:
就我个人而言,我更喜欢
(function(){})();
约定,因为它对我来说更明显该函数是自动执行的;我也是 jQuery 的大用户,这是 jQuery 源代码中使用的约定。此外,无论您选择使用哪种形式,使用括号括起自执行函数都被认为是一种很好的做法。
As far as differences go, it is really just syntactic sugar. Somewhat equivalent to: "do you like jQuery() or $()?" Both can be compiled, executed, and used interchangeably (AFAIK).
From the code samples I have seen thus far, more people seem to follow the Crockford code convention:
Personally, I prefer the
(function(){})();
convention because it is more apparent to me that the function is self-executing; I'm also a big user of jQuery and that's the convention used in jQuery source.Additionally, it is considered good practice to use parens to enclose your self-executing function, regardless of which form you choose to go with.