It forces the parser to treat the part following the +
as an expression.
(它强制解析器将+
的部分视为表达式。)
This is usually used for functions that are invoked immediately, eg: (通常用于立即调用的函数,例如:)
+function() { console.log("Foo!"); }();
Without the +
there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function
looks like the beginning of a function declaration rather than a function expression and so the ()
following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example).
(如果没有+
在那里,如果解析器是在它期待一个语句(可以是一个表达式或几个非表达式语句),字的状态function
看起来像函数声明的开始,而不是一个函数表达式等等()
后面的()
句号(上面一行的末尾)将是语法错误(在该示例中,缺少名称也是如此)。)
With the +
, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid. (使用 +
,使其成为函数表达式,这意味着名称是可选的,并且导致对该函数的引用,该引用可以被调用,因此括号是有效的。)
+
is just one of the options.
(+
只是选项之一。)
It can also be -
, !
(也可以是-
!
)
, ~
, or just about any other unary operator. (, ~
或几乎其他任何一元运算符。)
Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically): (或者,您可以使用括号(这是更常见的,但是在语法上既不正确,也不正确):)
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…