[英]Why doesn't const App = App || {}; work but using var does?
In the past I have used 过去我用过
var App = App || {};
to assign or instantiate a common App object in various js scripts loaded separately into the browser. 在分别加载到浏览器中的各种js脚本中分配或实例化公共App对象。
However, using let
and const
instead of var
throws a reference error: 但是,使用
let
和const
而不是var
会引发引用错误:
const App = App || {}; // or let App = App || {};
Uncaught ReferenceError: App is not defined
at <anonymous>:1:11
What's going on here? 这里发生了什么? If I want to continue using this pattern, do I have to stick to
var
? 如果我想继续使用这种模式,我是否必须坚持使用
var
?
This is because when you are declaring a variable using let
or a constant, the variable is in the temporal dead zone before being initialized. 这是因为当您使用
let
或常量声明变量时,变量在初始化之前处于时间死区 。
In other words, trying let foo = foo
will throw an error because foo
is still in the temporal dead zone, and cannot be used. 换句话说,尝试
let foo = foo
会抛出错误,因为foo
仍处于暂时死区,并且无法使用。 The same goes for const
. const
。
Note also that a variable defined whith let
or a constant defined with const
cannot share its name space in the same scope with another variable, be it with let
, const
, or var
. 还需要注意的是定义的变量蒙山
let
或定义的常数const
不能与其他变量相同的范围内分享它的名字空间,无论是let
, const
,或var
。
When javascript engine sees the statement, var App = App || {}
当javascript引擎看到语句时,
var App = App || {}
var App = App || {}
, it breaks the statement down as follows: var App = App || {}
,它将语句分解如下:
var App;
App = App || {};
Due to variable hoisting, var App = App || {}
由于可变提升,
var App = App || {}
var App = App || {}
is broken down into two parts. var App = App || {}
分为两部分。
var App
var App
App = App || {}
App = App || {}
App = App || {}
The let
and const
declarations on the other hand, don't involve variable hoisting. 另一方面,
let
和const
声明不涉及变量提升。 Hence, the ReferenceError
, as no variable called App exists yet. 因此,
ReferenceError
,因为还没有名为App的变量。
var
is behaving differently than let
or const
. var
的行为与let
或const
不同。
In case of var
, JS engine first creates a variables definitions, allocate memory space for them and initialize them with an undefined
value. 在
var
情况下,JS引擎首先创建变量定义,为它们分配内存空间并使用undefined
值初始化它们。 Only then it start executing the code line by line. 只有这样它才能逐行开始执行代码。
In case of let
or const
, it initialize it to undefined
only when the declaration actually happens (and only if there is no immediately assignment). 在
let
或const
情况下,它仅在声明实际发生时(并且仅在没有立即赋值时)将其初始化为undefined
。
In your example, the variable App
is still in the Temporal Dead Zone and trying to access it at that point results in a Reference Error. 在您的示例中,变量
App
仍处于Temporal Dead Zone中,并且在该点尝试访问它会导致参考错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.