【问题标题】:Undeclared assignment of variables are accessed outside of the function scope in JavaScript?在 JavaScript 的函数范围之外访问未声明的变量赋值?
【发布时间】:2016-02-21 14:43:24
【问题描述】:

通常,在函数内部声明的变量(变量声明)只能由该函数及其内部函数访问。但是,函数内部变量的未声明赋值是在 JavaScript中的函数作用域之外访问的> 通过使其成为全局变量。为什么会这样?

var hello = function() {
   number = 45;
};
hello();
console.log(number);    // 45 is printed in the console

【问题讨论】:

    标签: javascript variables scope


    【解决方案1】:

    因为规范是这么说的。

    "use strict"; 添加到文件或函数的顶部以禁止此操作。

    【讨论】:

      【解决方案2】:

      对未出现在var 声明中的变量的赋值被视为对全局变量(全局上下文的属性)的赋值。在“严格”模式下,这样的赋值会引发错误。

      这就是 JavaScript 的工作原理。如果 number 被正确声明,它将不会在全局范围内可见:

      var hello = function() {
         var number = 45;
      }
      hello();
      console.log(number);    // undefined is printed in the console
      

      【讨论】:

        猜你喜欢
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多