0

我有这段代码

var a = 5;
function woot(){
    console.log(a);
    var a = 6;
    function test(){ console.log(a);}
    test();
  };
woot();

我期待 5 和 6 作为输出,但我有 undefined 和 6 代替。

有什么想法吗?。

4

3 回答 3

4

变量声明被提升到它们出现的范围的顶部。您的代码解释如下:

var a; // Outer scope, currently undefined
a = 5; // Outer scope, set to 5

function woot(){ // Function declaration, introduces a new scope
    var a; // Inner scope, currently undefined
    console.log(a); // Refers to inner scope 'a'
    a = 6; // Inner scope, set to 6
    function test(){ console.log(a);} // Refers to inner scope 'a' (now 6)
    test();
  };
woot();

当您在函数内声明变量时,该变量将隐藏任何具有相同标识符的变量,该标识符已在祖先作用域中声明。在您的示例中,您a在全局范围内声明。然后在函数范围内声明另一个具有相同标识符的变量woot。此变量会隐藏a您在全局范围内声明的变量。

于 2013-04-28T21:59:38.943 回答
0

变量声明(var关键字)在您的函数范围内被提升woot,使其成为局部变量(隐藏全局变量a)。它将被初始化为undefined,并返回该值,直到您分配给它。

于 2013-04-28T22:01:55.273 回答
0

在那个时间:

function woot(){
console.log(a);

..a还不存在!如果你想使用外部a,你需要这样称呼它:

console.log( window.a );

删除a你已经在函数中的你可以使用,现在放松,console.log(a);将引用外部函数(因为你的函数中没有了)

否则,用于console.log( window.a );区分两者alphas

于 2013-04-28T23:01:16.673 回答