【问题标题】:Function, Global Variable, and Local Variable [duplicate]函数、全局变量和局部变量
【发布时间】:2019-03-14 14:36:49
【问题描述】:

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

【问题讨论】:

  • 您在 test() 函数中创建了一个局部 x,但编辑了全局 y。
  • @Quentin 这与“var”的含义无关。这是关于可变阴影的。对于初学者来说,这是两件非常不同的事情。
  • @MY_Chen 因为我不能留下答案,我就在这里提一下。这称为变量阴影,也与范围有关。这个问题讲了:stackoverflow.com/questions/11901427/…

标签: javascript function variables


【解决方案1】:

这是因为通过声明 var x = 30;,您创建了一个名为 x 的变量,该变量仅存在于函数的范围内。

然而,变量y 仅在顶层定义。因此,当您运行函数test 时,您编辑了本地x 变量和全局(顶级)y 变量。

【讨论】:

    【解决方案2】:

    当您定义变量时,它们会被提升到其范围的顶部。让我向您展示您当前的代码:

    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 的工作方式不同。它们的范围在块中。您可以在此处链接的相应链接中阅读它们。

    【讨论】:

    • 这篇文章被标记为重复。但我必须对此作出解释。因此,重新打开帖子并再次标记为重复。对不起!
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2019-07-24
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多