javascript 闭包中的 (...()) 与 (...)() [英] (...()) vs. (...)() in javascript closures

查看:25
本文介绍了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.

答案太酷了.~functionJSHint 替代品以及 jQuery 对 (/***/)(); 和 Crockford 的解释!我以为我只会得到它们是同一回事"之类的答案.
你们通过投票决定最好的一个,我勾选它.

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.

请注意,+! 也可以使用,有时会被缩小器用来保存大小的字符:

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';  
}();

编辑

正如@copy 指出的那样,为了完整性,~- 也可以使用.

As @copy points out, for completeness, ~ and - will also work.

-function() {  
    var foo = 'bar';  
}();

~function() {  
    var foo = 'bar';  
}();

这篇关于javascript 闭包中的 (...()) 与 (...)()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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