问题描述
+ ,它使它成为一个函数表达式,这意味着该名称是可选的,并且可以引用该函数,该函数可以是所以括号是有效的。
+ 只是其中一个选项。它也可以是 - ,!,〜或几乎任何其他一元运营商。或者,你可以使用圆括号(这是比较常见的,但在句法上既不多也不少):
pre $ (function(){ console.log(Foo!);})();
//或
(function(){console.log(Foo!);}());
I've been looking on info about self-invoking functions, and somewhere I stumbled on this notation:
+function(){}
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!"); }();
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加号在函数名前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!