我正在尝试解决一些代码片段,发现以下片段有点棘手。
var x =100;
function test() {
if(false) {
var x = 200;
}
console.log(x);
}
test();
我预计它会控制台 100 但它打印未定义,我真的不明白这里的提升是如何发生的,因为 false block 永远不会执行。谁能帮我了解这里的逻辑。
最佳答案
对,是JS hoisting导致的。在ES2015/6之前(let
/const
都是类似java的 block 作用域),JS中变量的作用域是函数作用域,即所有声明在函数中的变量将移至您的功能顶部
var x =100;
function test() {
if(false) {
var x = 200;
}
console.log(x);
}
test();
将被解释为:
var x =100; // global var
function test() {
var x; // local var
if(false) {
x = 200;
}
console.log(x); // climbing up the scope chain resolves to the closest local x, which is undefined.
}
test();
关于javascript - Javascript 提升问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530212/