为什么这种函数调用在JavaScript中是错误的? [英] Why this kind of function invocation is wrong in JavaScript?
问题描述
我想创建一个匿名函数,然后立即调用它。
1)这会带来语法错误。为什么?
function()
{
alert(hello);
}();
2)用()包装函数定义并且它可以工作。
(function()
{
alert(hello);
})();
<3>或者,将匿名函数赋值给一个变量。它可以工作。
pre $ code var dummy = function()
{
alert(hello);
}();
为什么第一种方式不起作用?
ECMAScript Language Specification ,第12.4节说:
表达式语句不能用 code> function 关键字,因为
可能会使它与
FunctionDeclaration 不一致。
所以你的情况1是不允许的,因为它可能会导致语言中的含糊不清。其他情况是不同类型的语句(而不是表达式语句),这不是问题,所以构造允许在那里。
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?
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.
这篇关于为什么这种函数调用在JavaScript中是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!