【问题标题】:let in if without braces如果没有大括号,请输入
【发布时间】:2015-12-18 04:41:11
【问题描述】:
if (true) {
  let x = 5
}

按预期工作(没有语法错误),但是

if (true) let x = 5

在 Node 4.1.0 和 babel 中抛出 SyntaxError: Unexpected strict mode reserved word

这是预期的行为吗?我知道这是一个愚蠢的例子。我只是想知道这是否是一个错误。

【问题讨论】:

  • 因为let 是基于块的,上面不是块,我认为错误是不可避免的。无论如何,您将无法在此声明之后使用let,因为这是一个单行“块”。
  • 如果您考虑一下,这是有道理的。即使这里有 块作用域,那么块作用域变量在其中有什么用呢?因为你永远无法使用它
  • 好的,预期的和合理的行为。谢谢。
  • 当我在 Firefox 中尝试这样做时,我收到一条更重要的错误消息:SyntaxError: lexical declaration not directly within block
  • @Guffa 这绝对是一个更好的错误信息。

标签: javascript node.js ecmascript-6 babeljs


【解决方案1】:

是的,这是预期的行为。 The production rule of an if statement

 if ( Expression[In, ?Yield] ) Statement[?Yield, ?Return]

但是 let 声明 is not a Statement 因此不允许在这个位置:

Statement[Yield, Return] :
    BlockStatement[?Yield, ?Return]
    VariableStatement[?Yield]
    EmptyStatement
    ExpressionStatement[?Yield]
    IfStatement[?Yield, ?Return]
    BreakableStatement[?Yield, ?Return]
    ContinueStatement[?Yield]
    BreakStatement[?Yield]
    [+Return] ReturnStatement[?Yield]
    WithStatement[?Yield, ?Return]
    LabelledStatement[?Yield, ?Return]
    ThrowStatement[?Yield]
    TryStatement[?Yield, ?Return]
    DebuggerStatement

Declaration[Yield] :
    HoistableDeclaration[?Yield]
    ClassDeclaration[?Yield]
    LexicalDeclaration[In, ?Yield]

LexicalDeclaration[In, Yield] :
    LetOrConst BindingList[?In, ?Yield] ;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2016-07-17
相关资源
最近更新 更多