【问题标题】:Value of variable changes when page reloads页面重新加载时变量的值发生变化
【发布时间】:2016-07-07 14:45:49
【问题描述】:

在编写简单函数声明时,Firefox Scratchpad 有一个奇怪的行为。

console.log(x);
var x = 0;
var func = function() {
  console.log(y);
  var y = 1;
};
func();

当我第一次使用 Run 执行上述代码时,结果如下:

未定义未定义

但是当我第二次执行它时,它给出了以下结果:

0 未定义

所以我假设该值必须保存在缓存中,但是为什么变量 y 仍然未定义?

当我用 Reload and Run 重复它时,第一个结果被重复了。

【问题讨论】:

    标签: javascript firefox firefox-developer-tools scratchpad


    【解决方案1】:

    都是关于var top-hoisting。和函数的块作用域

    当您第一次运行时,您的代码实际上看起来像这样。

    var x;
    console.log(x); // undefined as  still x is not defined
    x = 0;
    var func = function() {
       var y;
      console.log(y); //undefined as still y is not defined
      y = 1;
    };
    func();
    

    现在,当您第二次重新运行时,func() 的状态不会改变,因为它重新定义了 func 的块范围 所以在第二次运行时

    var func = function() {
       var y;
      console.log(y); //undefined as still y is not defined 
                      //as scope is re-initializd 
      y = 1;
    };
    

    在javascript中,每个函数在被调用时,都会创建一个新的执行上下文

    但作为var x; declared and defined in global scope 在第一次执行期间,它是从那里获取的。所以,x=0 and y=undefined

    【讨论】:

      【解决方案2】:

      自从你第一次执行那次以来,在使用它之前没有声明 x 和 y 变量。 一旦涉及到第二行,x 就被声明为全局,它保留在您的页面脚本中。但是对于 y 变量,它是在函数内部声明的,它的范围仅限于函数,因此 y 不会是全局的。

      因此,当您刷新页面时,x 变量会获得该全局值,但在 y 的情况下则不会。 这都是关于 Javascript 中变量的范围

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-10
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 2014-12-31
        相关资源
        最近更新 更多