为什么 JavaScript 中这种函数调用是错误的?

发布于 2024-07-15 18:15:37 字数 353 浏览 4 评论 0原文

我想创建一个匿名函数,然后立即调用它。

1)这会带来语法错误。 为什么?

function ()
{
    alert("hello");
}();

2)用 () 包装函数定义并且它可以工作。

(function ()
{
    alert("hello");
})();

3) 或者,将匿名函数赋给一个变量。 有用。

var dummy = function()
{
    alert("hello");
}();

为什么第一种方法行不通?

I'd like to create an anonymous function and then invoke it immediately.

1) This will bring a syntax error. Why?

function ()
{
    alert("hello");
}();

2) wrap the function definition with () and it works.

(function ()
{
    alert("hello");
})();

3) or, assign the anonymous function to a variable. It works.

var dummy = function()
{
    alert("hello");
}();

Why the first way doesn't work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一片旧的回忆 2024-07-22 18:15:37

ECMAScript 语言规范第 12.4 节指出:

ExpressionStatement无法启动
使用 function 关键字,因为
可能会使其变得含糊不清
函数声明

所以你的情况1是不允许的,因为它可能会导致语言中的歧义。 其他情况是不同类型的语句(不是ExpressionStatement),其中这不是问题,因此允许在那里构造。

The ECMAScript Language Specification, section 12.4, says:

An ExpressionStatement cannot start
with the function keyword because that
might make it ambiguous with a
FunctionDeclaration.

So your case 1 is not allowed, because it might lead to ambiguities in the language. The other cases are different kinds of statements (not ExpressionStatements) in which this is not a problem, so the construct is allowed there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文