JavaScript 函数表达式前的加号 [英] JavaScript plus sign in front of function expression
问题描述
我一直在寻找有关立即调用函数的信息,并且在某处偶然发现了这个符号:
I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
有人可以向我解释一下函数前面的 +
符号是什么意思吗?
Can someone explain to me what the +
sign in front of the function means/does?
推荐答案
它强制解析器将 +
后面的部分视为表达式.这通常用于立即调用的函数,例如:
It forces the parser to treat the part following the +
as an expression. This is usually used for functions that are invoked immediately, e.g.:
+function() { console.log("Foo!"); }();
如果没有 +
,如果解析器处于期望语句(可以是表达式或多个非表达式语句)的状态,则单词 function
看起来像一个函数声明的开始,而不是一个函数表达式,所以它后面的()
(在上面的行)将是一个语法错误(在该示例中,名称的缺失也是如此).使用 +
,它使它成为一个函数表达式,这意味着名称是可选的,并且导致对函数的引用,该函数可以被调用,因此括号是有效.
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). 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!"); }());
这篇关于JavaScript 函数表达式前的加号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!