Lexical declaration cannot appear in a single-statement context

时间:2019-11-05
本文章向大家介绍Lexical declaration cannot appear in a single-statement context,主要包括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.

原文地址:https://www.cnblogs.com/indeeds/p/11797880.html