JavaScript范围在这里发生了什么?

Ove*_*erv 8 javascript scope

我写了以下代码片段:

var f = function() { document.write("a"); };

function foo() {
    f();

    var f = function() { document.write("b"); };
}

foo();
Run Code Online (Sandbox Code Playgroud)

我期望打印的函数a被调用,但它反而给出了一个关于调用undefined值的运行时错误.为什么会这样?

小智 14

这是关于变量吊装http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html,http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

你的代码与下一代的代码相同;

var f = function() { document.write("a"); };
function foo() {
    //all var statements are analyzed when we enter the function
    var f;
    //at this step of execution f is undefined;
    f();
    f = function() { document.write("b"); };
}
foo();
Run Code Online (Sandbox Code Playgroud)