我知道下面的代码片段会导致 ReferenceError:
console.log(b);
let b = 3;
而且我读到如果我们使用 var
而不是 let
就不会失败。
MDN documentations , 声明 let 声明也被提升,但它们没有被初始化
令我困惑的是初始化,当我们谈论 ReferenceError 时它甚至有什么关系。
在下面的代码中,
let b;
console.log(b);
b = 3;
初始化是在 console.log(b)
之后写的,但这不会产生任何 ReferenceError,所以说在第一个代码片段中抛出异常是没有意义的,因为变量未初始化。
谁能澄清一下这些事情吗?
最佳答案
The
let
(andconst
) declaration will throw an error if accessed before initialized.
这是什么意思?
如果您尝试在程序到达声明行之前访问变量,您将得到一个错误:
try{
console.log(b)
}catch(e){
console.error(e) //ReferenceError
}
let b //b initalized here (b===undefined)
console.log(b) //undefined
b=3 //Reassign b with 3
console.log(b) //3
即使 let
缺少 =value
部分,初始化也会发生,在这种情况下,值为 undefined
,所以它不会不再抛出错误。
这就是为什么你不能从 const
声明中省略 =value
部分:它将被初始化为 undefined
而不能稍后重新分配。
另请注意这种错误与尝试访问未定义变量时的错误不同:即使定义了变量(在另一个范围):
let b=1
console.log(b) //1
{
//Different scope
try{
console.log(b)
}catch(e){
console.error(e) //ReferenceError: the inner b shadows the outer, but not yet initialized
}
let b=2
console.log(b) //2
}
关于javascript - let 声明被提升但未初始化是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58786369/