2014-03-12 63 views
1

首先,我想说我正在搜索有关javascript范围变量的一些信息(例如What is the scope of variables in JavaScript?),我试图理解为什么我的代码的行为如此,但最后我真的不知道。我不能在函数中重写var a,我只能使用a = 6;而不使用var。为什么a在if语句之前未定义并覆盖此变量?为什么会出现这样的没有结果:覆盖javascript函数中的变量

等于5
等于6

我有这样的事情,而不是:

不确定

不等于5
等于6

这里是我的代码:

var a = 5; 

function something(){ 
    console.log(a); 
    if(a == 5){ 
     console.log('equal 5') 
    } 
    else{ 
     console.log('not equal 5'); 
    }  
    var a = 6; 

    function test(){ 
     if(a == 6){ 
     console.log('equal 6'); 
    } 
    else{ 
     console.log('not equal 6') 
    } 
    }  
    test();  
} 
something(); 

回答

5

这是因为JavaScript变量提升。

您的代码等于:

var a = 5; 

function something(){ 
    var a; // here 
    console.log(a); // a is the local variable which is undefined 
    if(a == 5){ 
     console.log('equal 5') 
    } 
    else{ 
     console.log('not equal 5'); // a is undefined so not equal 5 
    }  

    a = 6; // a is assigned to 6 

    function test(){ 
     if(a == 6){ 
      console.log('equal 6'); // a is 6 here 
     } 
     else{ 
      console.log('not equal 6') 
     } 
    }  
    test();  
} 
something(); 
1

因为当你声明var a = 6你第二次被覆盖的a第一个声明,即var a = 5。所以当你定义函数something()时,a尚未定义,因此console.log(a)返回undefined。

然而,当你刚刚a = 6第一个声明仍然有效替代的a第二个声明,你只需要改变的a值之后,所以你得到预期的结果:

5 
equal 5 
equal 6 

this post更多的讨论。