首页 > 移动平台 > 详细

Lexical declaration cannot appear in a single-statement context

时间:2019-11-05 14:12:02      阅读:285      评论:0      收藏:0      [点我收藏+]

代码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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!