【问题标题】:variable difference between function scope javascript函数范围javascript之间的变量差异
【发布时间】:2016-10-15 02:55:43
【问题描述】:

我正在阅读有关javascript的执行上下文和范围的主题。下面是一个简单的代码:

 var scope="global";  
    function t(){  
        alert(scope);  // alert :"undefined"
        var scope="local" ; 
        alert(scope);  // alert: "local"
    }  
    t();  

如果我删除 'var scope="local" ; ' ,它会变成这样:

var scope="global";  
function t(){  
    alert(scope);  // alert :"global"   
}  
t();  

我不明白为什么在我删除函数 t() 中的 var scope="local" 后,在第二种情况下范围的值会更改为“global”。

谁能帮忙解释一下,谢谢!

【问题讨论】:

  • 你明白为什么第一个例子中拳头alert显示undefined了吗?
  • @DiegoCardoso 我实际上不明白。介意发布一个示例链接吗?
  • @RobScott 这是因为吊装。函数中定义的任何变量都被提升到该函数的顶部。因此,在这种情况下,他重新定义了同一个变量,但在第一行,scope 尚未初始化。您可以查看@Tim 答案中的链接。
  • @Steven Liang 你能接受答案吗?

标签: javascript variables scope


【解决方案1】:

当你这样做时:

scope = 'global'
function t() {
  alert(scope) // undefined
  var scope = 'func'
  alert(scope) // func
}
t()

var scope... 行,你告诉js:小心,我在这个函数中定义了“范围”。所以 JS 重置它的值(未定义)。就像你这样做了:

scope = 'global'
function t() {
  var scope; // erase previous 'scope', so it is now undefined
  alert(scope) // undefined
  scope = 'func'
  alert(scope) // func
}
t()

但如果你只是这样做

scope = 'global'
function t() {
  alert(scope) // global
}
t()

您没有在函数中创建变量 scope,因此 JS 不会删除它的值,当您尝试访问它时,JS 会尝试找到更高的变量(在这种情况下是在全局命名空间中)

希望你明白...这确实有点奇怪,因为首先,JS 会查找你在函数中声明的每个变量(并重置/初始化它们)然后 然后 运行你的函数。

马特

【讨论】:

    【解决方案2】:

    基本上,在您的第一个示例中,scope 的范围(即函数内部声明的 var)是函数 t 的整个主体。它在到达var scope == ... 行之前没有值,但它是从一开始就定义的。

    所以alert(scope) 将“范围”解析为本地定义的变量,它还没有值——也就是说,它是undefined

    看到这个问题

    The benefits of declaring variables at the top of the function body in JavaScript

    更多解释。

    【讨论】:

      【解决方案3】:
      var scope="global";  
      function t(){ 
          // you redefine variable scope here
          // so, the global one is not visible.
      
          alert(scope);  // alert :"undefined"
          alert(window.scope); //alert: "global"
          var scope="local" ; 
          alert(scope);  // alert: "local"
      }  
      t();  
      

      【讨论】:

        【解决方案4】:

        这是因为 javascript 中称为提升的概念。函数 t() 中的变量范围被提升到函数的开头,即它被初始化为 undefined,然后分配给它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-24
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 2021-06-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多