变量可见吗?
重要性:4
这段代码的结果是什么?
let
x =
1
;
function
func
(
)
{
console.
log
(
x)
;
// ?
let
x =
2
;
}
func
(
)
;
P.S. 这道题有一个陷阱。答案并不明显。
结果是:错误。
尝试运行它
let
x =
1
;
function
func
(
)
{
console.
log
(
x)
;
// ReferenceError: Cannot access 'x' before initialization
let
x =
2
;
}
func
(
)
;
在这个例子中,我们可以观察到“不存在”和“未初始化”变量之间的特殊区别。
正如您可能在文章变量作用域,闭包中读到的那样,变量从执行进入代码块(或函数)的那一刻起就处于“未初始化”状态。并且它一直保持未初始化状态,直到相应的let
语句。
换句话说,变量在技术上存在,但在let
之前不能使用。
上面的代码演示了这一点。
function
func
(
)
{
// the local variable x is known to the engine from the beginning of the function,
// but "uninitialized" (unusable) until let ("dead zone")
// hence the error
console.
log
(
x)
;
// ReferenceError: Cannot access 'x' before initialization
let
x =
2
;
}
这个变量暂时不可用的区域(从代码块的开头到let
)有时被称为“死区”。