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.