当在 if 块范围内用关键字 var 声明的变量发生提升时,( var x;) 是否提升到当前 if 块的顶部?或者在这种情况下到全局范围的顶部?假设我们直接在全局作用域内写了下面这段代码
if (true) {
some code;
var x = 1;
}
根据您的示例使用var
(或完全省略定义键,例如 just x = 1
)时,它将被提升到最近的范围,在您的示例中将是全局范围 ( window
)。
如果它将被包装在一个函数中,那么该函数将是最接近的作用域。
function a() {
if(true){
var x=1;
}
console.log(x) // 1
console.log(window.x) // undefined
}
a()
console.log(x) // Throws error (x is not defined)
如果您希望变量完全是块作用域,那么您需要使用let
or const
。
if(true){
const x=1;
}
console.log(x) // Throws error (x is not defined)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句