函数表达式前面的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
看起来像函数 declaration 而不是函数 expression ,因此其后的()
(位于上一行的末尾)将是语法错误(缺少名称) ,在该示例中). 使用 +
,使其成为函数表达式,这意味着名称是可选的,并且导致对该函数的引用,该引用可以被调用,因此括号是有效的.
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屋!