奇怪的javascript范围问题

时间:2013-07-15 19:40:34

标签: javascript scope

var c = 1;

function myFunction(){
    c = 2;
    var c = 4;
    console.log(c);
}

console.log(c);
myFunction();
console.log(c);

为什么最后一个console.log吐出1?以下是它应该如何在我的大脑中起作用:

var c = 1; // create global variable called 'c'

function myFunction(){
    c = 2; // assign value of global 'c' to 2
    var c = 4; // create a new variable called 'c' which has a new address in memory (right?)  with a value of 4
    console.log(c); // log the newly created 'c' variable (which has the value of 4)
}

console.log(c); //log the global c
myFunction(); //log the internal c
console.log(c); //log the updated global c

1 个答案:

答案 0 :(得分:3)

在运行console.log的范围内,仅存在全局变量。函数永远不会触及全局变量。

细节:

var c = 1; // create global variable called 'c'

function myFunction(){
    // the global is unavailable here, as you declared a local c.
    // Its declaration is hoisted to the top of the function, so
    // c exists here, and its value is undefined.
    c = 2; // assign value of local 'c' to 2
    var c = 4; // change local c to 4
    console.log(c); // log local c (4)
}

console.log(c); //log the global c
myFunction(); //log the internal c
console.log(c); //log the global c (which never changed)

由于上面提到的提升,您的功能就像代码是:

function myFunction(){
    var c; // declares a local c that shadows the global one
    c = 2;
    c = 4;
    console.log(c);
}

有关吊装的一些参考资料