3

我想知道,初始化对象时附加括号的意义是什么。例如:

var foo = function(){ ... }();

相对

var foo = (function(){ ... }());

我假设一些与范围有关的东西,但我想知道是否有人可以更准确地了解具体差异,因为它们似乎都是根据每个匿名函数返回的内容来初始化一个对象。

4

3 回答 3

5

In that specific case, there's no effective difference.

Some people like the outer (...) because it gives them a visual hint near the = operator that the function is being invoked.

But the assignment operator causes the function to be evaluated as the expression that is the right hand operand of the assignment operator, and as such it can be invoked without any further need to coerce it out of a function declaration.


Without the assignment, there needs to be some syntax involved that lets the interpreter know that the function keyword is being used as an anonymous function expression.

For example...

(function() {
   // code
})();

Here the parentheses resolved the ambiguity of function so that it's treated as the single expression inside the (...) group.


The grouping operator is just one way of forcing a function to be evaluated as an expression. Most JavaScript operators can be used for this purpose. Unary operators are probably safest, for example...

!function() {
   // code
}();

...or...

void function() {
   // code
}();

In both cases, the function is seen as the single operand to the respective operator.

于 2012-04-09T19:26:02.067 回答
2

两者在功能上是等效的。

然而,作为惯例,许多程序员更喜欢用左括号来表示 var 是函数的结果,而不是函数本身。

自调用函数的使用是传入变量来保存它们的“命名空间”,例如传入window或document,或者jquery之类的其他东西是很常见的。

根据对 jslint 的一些快速测试,这样做的首选方式是以下测试中的第一个 (foo)。

var foo = (function () {}());
var bar = (function () {})();
var baz = function () {}();

请注意,调用 () 在外括号内。

JSLint 为 bar 和 baz 提供以下错误

错误:

第 2 行字符 28 处的问题:将调用移动到包含函数的括号中。

var bar = (function (w) {})(window);

第 3 行字符 27 处的问题:将立即函数调用括在括号中,以帮助读者理解表达式是函数的结果,而不是函数本身。

var baz = 函数 (w) {}(窗口);

于 2012-04-09T19:41:49.150 回答
0

据我所知,这只是一个约定,并不是绝对必要的。

这是一篇很好的文章,说明了为什么这个约定很有用:

http://peter.michaux.ca/articles/an-important-pair-of-parens

于 2012-04-09T19:22:08.047 回答