(...())vs.(...)()在javascript闭包 [英] (...()) vs. (...)() in javascript closures

查看:122
本文介绍了(...())vs.(...)()在javascript闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是愚蠢的,但这之间有任何区别:

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屋!

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