(...())vs.(...)()在javascript闭包 [英] (...()) vs. (...)() in javascript closures
问题描述
我知道这是愚蠢的,但这之间有任何区别:
I know this is silly, but there's any difference between this:
(function() {
var foo = 'bar';
})();
和此?
(function() {
var foo = 'bar';
}());
JSLint 告诉我们将调用移动到包含函数
的括号中,但我看不需要。
JSLint tells us to Move the invocation into the parens that contain the function
, but I see no need to.
修改:答案太酷了。 〜function
, JSHint 替代方法以及jQuery对(/ *** /)();
和Crockford的解释!我想我会得到一个他们是同样的事情的答案。
你们通过upvote决定最好的一个,然后点击它。
The answers are too cool. ~function
, the JSHint alternative along with jQuery's preference for (/***/)();
and Crockford's explanation! I thought I was going to just get a "they're the same thing" kind of answer.
You guys decide the best one through upvotes and I tick it.
推荐答案
没有区别。两种方法都是使JavaScript解析器将您的函数作为表达式而不是声明处理的有效方式。
There's no difference. Both are valid ways to get the JavaScript parser to treat your function as an expression instead of a declaration.
注意, +
和!
也可以工作,有时被缩小器用来保存一个大小的字符: p>
Note that +
and !
will also work, and are sometimes used by minifiers to save a character of size:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
EDIT
As @copy指出,为了完整起见,〜
和 -
也可以工作。
As @copy points out, for completeness, ~
and -
will also work.
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
这篇关于(...())vs.(...)()在javascript闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!