gpt4 book ai didi

javascript - 函数在分配给变量时有效,但在其自身执行时抛出 SyntaxError

转载 作者:行者123 更新时间:2023-11-30 09:22:48 25 4
gpt4 key购买 nike

我有一个这样的 IIFE:

(function a() {
return "b";
}());

在控制台执行,返回"b"

我删除了第一组括号,认为这将使“a”函数成为全局函数,但仍然有效,并返回 “b”:

function a() {
return "b";
}();

但它会抛出一个SyntaxError:

Uncaught SyntaxError: Unexpected token )

然后,我尝试通过分配给一个变量来将函数转换为表达式,并且成功了:

var c = function a() {
return "b";
}();
console.log(c); // prints b

为什么会这样?为什么它作为表达式起作用而不是单独起作用?

最佳答案

第二段代码不是它看起来的样子。

这段代码看起来像一个正在立即执行的函数:

function a() {
return "b";
}()

但实际上,它只是一个函数声明后跟一个空表达式,这是不允许的:

function a() {
return "b";
}

() // not allowed - empty expression

Ben Alman 在他的 article 中解释了这一点在 IIFE 上:

When the parser encounters the function keyword in the global scope or inside a function, it treats it as a function declaration (statement), and not as a function expression, by default.

...

While parens placed after an expression indicate that the expression is a function to be invoked, parens placed after a statement are totally separate from the preceding statment, and are simply a grouping operator (used as a means to control precedence of evaluation).

分组运算符需要包含要计算的表达式。它本身没有任何意义:

() // meaningless
2 + 3 * 4 // 15
(2 + 3) * 4 // 20

在 IIFE 中,外括号只是一种强制解析器期待表达式的方法。

这就是表达式 var c = function() { return "b"; 的原因}(); 也有效;这是因为由于对 c 的赋值,解析器知道需要一个表达式。

旁注

Alman 还建议在分配给变量时不要使用不使用外括号的自调用函数(即 var v = function(){...}()),因为这是不好的做法:

In cases where the extra “disambiguation” parens surrounding the function expression are unnecessary (because the parser already expects an expression), it’s still a good idea to use them when making an assignment, as a matter of convention.

Such parens typically indicate that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself. This can save someone reading your code the trouble of having to scroll down to the bottom of what might be a very long function expression to see if it has been invoked or not.

关于javascript - 函数在分配给变量时有效,但在其自身执行时抛出 SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com