Why this kind of function invocation is wrong in JavaScript?

只谈情不闲聊 提交于 2019-12-17 16:38:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/670623/why-this-kind-of-function-invocation-is-wrong-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!