Lexical declaration cannot appear in a single-statement context

代码1

if (true) {
    var x = 1;
}

代码2

if (true)
    var x = 1;

代码3

if (true) {
    let x = 1;
}

代码4

if (true)
    var x = 1;

对于上述四段代码,代码4会报错 “Lexical declaration cannot appear in a single-statement context”,对此 TypeScript 的作者 Anders Hejlsberg 说:

JavaScript only permits let and const declarations within a block

Github Issue

有人评论说:

https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations
let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.
https://www.ecma-international.org/ecma-262/6.0/#sec-lexical-environments
A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.
https://www.ecma-international.org/ecma-262/6.0/#sec-declarative-environment-records
Each declarative Environment Record is associated with an ECMAScript program scope containing variable, constant, let, class, module, import, and/or function declarations.

想了想,对于 JavaScript 引擎来讲,完全可以把这种情况当做是在块作用域内声明变量,但这并无意义,因为这种情况下单行使用 let 声明变量,必然没有使用到这个变量的地方,如果有,那就必须使用大括号显式地表明是块作用域。所以在阮一峰老师的《ECMAScript6 入门》一书中有一句:

如果没有大括号,JavaScript 引擎就认为不存在块级作用域。

Lexical declaration cannot appear in a single-statement context

上一篇:JS中的call(),apply(),bind()方法


下一篇:鼠标移动跳转块悬浮样式