Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - 函数名称前的JavaScript加号(JavaScript plus sign in front of function name)

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?

(有人可以向我解释该功能前面的+号是什么意思吗?)

  ask by jOpacic translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!"); }());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...