代碼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
有人評論說:
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 引擎就認為不存在塊級作用域。