函数范围javascript

时间:2016-10-15 02:55:44

标签: javascript variables scope

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

 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"

有人可以帮忙解释一下,谢谢!

4 个答案:

答案 0 :(得分:3)

执行此操作时:

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

马特

答案 1 :(得分:2)

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

所以alert(scope)已解决"范围"作为本地定义的变量,它还没有价值 - 也就是说,undefined

看到这个问题

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

了解更多解释。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这是因为在javascript中称为提升的概念。函数t()中的变量范围被提升到函数的开头,它被初始化为未定义的,后来的本地'分配给它。

相关问题