我不明白为什么测试后的x不会变成30但仍然保持10
<script>
function test(){
var x = 30;
y = 40;
}
</script>
<script>
var x = 10;
var y = 20;
document.write("before test, x: " + x + ", y: " + y + "<br/><br/>");
test();
document.write("after test, x: " + x + ", y: " + y + "<br/><br/>");
</script>
答案 0 :(得分:1)
这是因为通过声明var x = 30;
,您创建了一个名为x
的变量,该变量仅存在于函数的作用域中。
但是,变量y
仅在顶级定义。因此,当您运行函数test
时,您将编辑本地x
变量和全局(顶级)y
变量。
答案 1 :(得分:0)
定义变量时,它们将被吊在其作用域的顶部。让我向您展示您当前的代码:
function test(){
var x = 30;
y = 40;
}
var x = 10;
var y = 20;
test();
将这样运行:
// global scope
var x; // x is undefined
var y; // y is undefined
function test() {
// function scope
var x; // x is undefined inside this scope
x = 30; // x is assigned with value 30
y = 40; // y is assigned with value 40
// the global scope y value is assigned
}
x = 10; // x is assigned with value 10
// the global scope x value is assigned
y = 20; // y is assigned with value 20
// the global scope y value is assigned
test();
// when calling test,
// you see x is assigned with its function scope
// and y is assigned with its global scope
// so, at this point
// x becomes 10
// y becomes 40
您可以在docs中阅读有关var
的更多信息。另外,请查看scope,global scope和local scope。