我写了以下代码片段:
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)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |