为什么JavaScript的null合并运算符(||)不能用于es6变量(let/const)?

Afs*_*5mm 1 javascript var let null-coalescing-operator ecmascript-6

为什么var APP = APP || {};工作正常,但const APP = APP || {};不是?或者let APP = APP || {}就此而言.

Uncaught ReferenceError: APP is not defined
Run Code Online (Sandbox Code Playgroud)

因为这只与APP的评估有关,而不是与它的设定有关.

Fel*_*ing 9

为什么var APP = APP || {};工作正常,但const APP = APP || {};不是?

让我们澄清一下如何评估这些陈述.在执行任何代码之前,运行时将查找所有变量声明,并为当前作用域中的每个声明创建一个条目.APP = APP || {}执行一段时间后,将在赋值APP之前读取值.

它"有效" var,因为var声明是用值隐式初始化的undefined.因此,在为其分配值之前访问变量将返回undefined.

constlet然而,声明未被初始化.在从初始声明中分配值之前,您无法访问它们.这也称为暂时死区或简称TDZ.

这是一个简化的例子:

console.log(foo); // undefined
var foo = 42;
console.log(foo); // 42
Run Code Online (Sandbox Code Playgroud)

VS

console.log(foo); // ReferenceError because of TDZ
let foo = 42;
console.log(foo); // 42 in theory, but this line is never executed due to the error above
Run Code Online (Sandbox Code Playgroud)