JavaScript 函数表达式前的加号

编程入门 行业动态 更新时间:2024-10-24 08:22:36
本文介绍了JavaScript 函数表达式前的加号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在寻找有关立即调用函数的信息,并且在某处偶然发现了这个符号:

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 函数表达式前的加号

本文发布于:2023-10-28 18:23:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加号   表达式   函数   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!