May function declarations appear inside statements in JavaScript?

后端 未结 7 1399
暖寄归人
暖寄归人 2020-11-29 04:34

Please consider the official ECMAScript specification as the source for your answer, and not a document published by a specific browser vendor. (I am aware of Mozilla extend

7条回答
  •  星月不相逢
    2020-11-29 05:26

    No, it's invalid. Function declarations can only appear as "source elements", which are either in the global scope or immediately within another function definition, outside all other statements. From the ECMA-262 spec:

    FunctionBody : SourceElements

    Program : SourceElements

    SourceElement : Statement | FunctionDeclaration

    There is no other production in the grammar that allows a FunctionDeclaration.

    Only function expressions are allowed to be part of a statement:

    MemberExpression : FunctionExpression

    ...

    Statement : ExpressionStatement

    Edit: There was a related discussion on another question recently. See the comments on this answer - earlier, I too thought that this could be valid but the grammar makes it clear that it is invalid.

提交回复
热议问题