May function declarations appear inside statements in JavaScript?

后端 未结 7 1202
暖寄归人
暖寄归人 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:30

    Version 5 of ECMA-262 says it shouldn't be valid:

    FunctionDeclarations are only allowed to appear in Program or FunctionBody. Syntactically, they can not appear in Block ({ ... }) — such as that of if, while or for statements. This is because Blocks can only contain Statements, not SourceElements, which FunctionDeclaration is. If we look at production rules carefully, we can see that the only way Expression is allowed within Block is when it is part of ExpressionStatement. However, ExpressionStatement is explicitly defined to not begin with "function" keyword, and this is exactly what makes FunctionExpression invalid as part of a Statement or Block (note that Block is merely a list of Statements).

    However, it seems not many interpreters obey this rule. Kangax says they should be considered syntactical errors per this page:

    Because of these restrictions, whenever function appears in a block (such as in previous example) it should actually be considered a syntax error, not function declaration or expression. The problem is that almost none of the implementations I've seen parse these functions strictly per rules (exceptions are BESEN and DMDScript). They interpret them in proprietary ways instead.

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