javascript - JavaScript 使用 let 和 var 关键字时的意外行为

标签 javascript

当我使用 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 with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. 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/

相关文章:

javascript - JS/jQuery - 根据用户输入显示结果

javascript - 如果我将 .on ('click' 事件附加到 $ ("body",性能会受到影响吗?

JavaScript - 原型(prototype)继承

javascript - 在 Javascript 中导入 Typescript 文件

javascript - 将 js knockout 到 mysql 数据库,使动态值不起作用

javascript - 如何从具有一个或多个类名的元素中查找恰好具有特定且唯一的类名(而不是任何其他类名)的元素?

javascript - Bluebird promise 未定义?

javascript - 将分配替换为延迟分配

javascript - Reactjs 按键正则表达式?

javascript - 在 <ul> 之间移动 Li