Why this kind of function invocation is wrong in JavaScript?

后端 未结 1 477
醉酒成梦
醉酒成梦 2020-12-06 13:41

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

1) This will bring a syntax error. Why?

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


        
相关标签:
1条回答
  • 2020-12-06 14:11

    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.

    0 讨论(0)
提交回复
热议问题