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

时间:2017-10-27 19:32:04

标签: javascript ecmascript-6 var let null-coalescing-operator

为什么var APP = APP || {};工作正常,但const APP = APP || {};没有?或let APP = APP || {}就此而言。

Uncaught ReferenceError: APP is not defined

因为这只与APP的评价有关,而与其设定的内容无关。

2 个答案:

答案 0 :(得分:9)

  

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

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

它"工作"使用var,因为var声明是使用值undefined进行隐式初始化的。因此,在为其赋值之前访问变量将返回undefined

然而,

constlet声明保留未初始化。在从初始声明中分配值之前,您无法访问它们。这也简称为temporal dead zone TDZ

这是一个简化的例子:



console.log(foo); // undefined
var foo = 42;
console.log(foo); // 42




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




答案 1 :(得分:1)

来自MDN

  

在ECMAScript 2015中,让绑定不受变量提升的约束,这意味着让声明不会移动到当前执行上下文的顶部。在初始化之前引用块中的变量会导致ReferenceError(与使用var声明的变量相反,该变量将具有未定义的值)。变量位于"临时死区"从块的开始直到处理初始化。

同样适用于const

  

关于"临时死区的所有考虑因素"适用于let和const。

换句话说,这是有效的原因:

Format("1267.5", "Currency")

是因为变量提升将上述内容翻译为:

var APP = APP || {};

由于变量提升不适用于var APP; // <-- declares APP APP = APP || {}; // <-- initializes APP let

const

最后,对于记录(正如naomik所指出的那样),const APP = APP || {}; // <-- Fails because APP is not yet initialized. let APP = APP || {}; // <-- Fails for the same reason. 运算符是一个空合并运算符,而是 short-电路OR运算符

对此的混淆可能是因为这样的陈述:

||

对于上述陈述,有两点需要注意。

  1. var n = n || ''; 不是n ...它是null(不同于 空)。

  2. 由于变量提升,该陈述相当于:

    undefined
  3. 因为var n; // n has the value of undefined n = n || ''; // the comparison is now: undefined || ''; 是一个&#34; falsy&#34;值,短路OR运算符返回第二个值。

    此行为也适用于undefined因为 null也是&#34; falsy&#34;。