当我使用 var 关键字声明变量时,JS 引擎会在创建阶段为“message”分配默认值
console.log(message); //undefined
var message = "My message";
但是使用let关键字
console.log(message); //message is not defined
let message = "My message";
为什么会出现这种意想不到的结果或者是 ES6 中发生了一些变化?
最佳答案
这是因为 Temporal dead zone 的创建与 let
let
bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared withvar
, which will start with the valueundefined
,let
variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in aReferenceError
. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.
关于javascript - JavaScript 使用 let 和 var 关键字时的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359621/