函数作用域之间的变量差异

variable difference between function scope javascript

本文关键字:变量 作用域 之间 函数      更新时间:2023-09-26

我正在阅读关于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"后,scope的值在第二种情况下更改为"global"。

有人可以帮助解释这个,谢谢!

当你这样做的时候:

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

var scope...行,你告诉js: 小心,我在这个函数中定义了'作用域'。所以JS重置它的值(undefined)。就像你那样:

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寻找你在函数中声明的每个变量(并重置/初始化它们),然后运行你的函数。

马特

本质上,在你的第一个例子中,scope的作用域(即在函数内部声明的var)是函数t的整个主体。它在到达var scope == ...行之前没有值,但它从一开始就定义了。

所以alert(scope)将"scope"解析为局部定义的变量,它还没有值-也就是说,它是undefined

参见这个问题

在JavaScript函数体顶部声明变量的好处

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();  

这是因为javascript中一个叫做提升的概念。函数t()中的变量作用域被提升到函数的开头,即它被初始化为undefined,然后将'local'赋值给它。