functionf() {
console.log(a);
let a = 2;
}
f(); // ReferenceError: a is not defined
复制代码
这段代码直接报错a is not defined,let和const拥有相似的特征,阻止了变量提高,当执行console.log(a)的时候变量没有定义,因此报错了。 在阮一峰老师的网站也写到let和const都是不存在变量提高的。以下 lua
,对此我也产生的疑问,发如今不一样的权威机构有着不同的解释。spa
MDN中写到:In ECMAScript 2015, let do not support Variable Hoisting, which means the declarations made using "let", do not move to the top of the execution block.
在MDN中认为let不存在变量提高3d
ECMA-262-13.3.1 Let and Const Declarations写到: let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
这说明即便是 block 最后一行的 let 声明,也会影响 block 的第一行。这就是提高(hoisting)code
ECMA-262: 8.2.1.2 Runtime Semantics: EvalDeclarationInstantiation( body, varEnv, lexEnv, strict)写到: The environment of with statements cannot contain any lexical declaration so it doesn't need to be checked for var/let hoisting conflicts.