This question already has answers here:
Javascript function scoping and hoisting
(16个答案)
7个月前关闭。
有人能帮我理解控制的流程吗。为什么输出242看起来应该是243。所有的帮助将不胜感激。
要在全局范围内真正更改变量,请使用
(16个答案)
7个月前关闭。
var x = 2;
function fun() {
x = 3;
var x = 4;
document.write(x);
}
document.write(x);
fun()
document.write(x);
有人能帮我理解控制的流程吗。为什么输出242看起来应该是243。所有的帮助将不胜感激。
最佳答案
当您修改x=3
时,实际上并没有改变全局变量x
,而是改变函数块中声明的变量(因为var
变量具有函数作用域)。当声明被提升到顶部,然后对var x
进行修改时
<script>
var x=2;
function fun(){
//var x; hoisted to the top;
console.log("x is hoisted here and uninitialized value will be", x)
x=3; //initialized, actually referring to the variable declared in the function scope
var x = 4; //declared but hoisted at the top
document.write(x);
}
document.write(x);
fun()
document.write(x);
</script>
要在全局范围内真正更改变量,请使用
x = 3
来引用它:<script>
var x=2;
function fun(){
window.x=3; //modifying the global variable 'x`
var x = 4;
document.write(x);
}
document.write(x);
fun()
document.write(x);
</script>
09-25 19:27