函数,全局变量和局部变量

时间:2019-03-14 14:36:49

标签: javascript function variables

我不明白为什么测试后的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>

2 个答案:

答案 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的更多信息。另外,请查看scopeglobal scopelocal scope


此外,请注意letconst的工作方式有所不同。它们在该范围内。您可以在此处链接的相应链接中阅读它们。

相关问题