<分区>
我编写了以下代码片段:
var f = function() { document.write("a"); };
function foo() {
f();
var f = function() { document.write("b"); };
}
foo();
我希望调用打印 a
的函数,但它却给出了关于调用 undefined
值的运行时错误。为什么会这样?
标签 javascript scope
<分区>
我编写了以下代码片段:
var f = function() { document.write("a"); };
function foo() {
f();
var f = function() { document.write("b"); };
}
foo();
我希望调用打印 a
的函数,但它却给出了关于调用 undefined
值的运行时错误。为什么会这样?
最佳答案
关于变量提升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();
关于javascript - 这里的 JavaScript 作用域是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499825/