我的一个朋友正在参加在线测验,他问了我这个问题,我无法回答。
var global = false;
function test() {
global = true;
return false;
function global() {}
}
console.log(global); // says false (As expected)
test();
console.log(global); // says false (Unexpected: should be true)
如果我们假设函数与 var 变量一起被提升到顶部,那么让我们尝试一下这个。
var foo = 1;
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = 11;
}
bar();
console.log(foo); //says 1 (But should be 11) Why 1 this time ??
这里有一个JSBin 演示 http://jsbin.com/tope/1/edit?html,js,console,output and JSBIN演示2 http://jsbin.com/tope/4/edit?js,console,output和玩。
PS:如果我们删除function global() {}
from test()
,然后就可以正常运行了。有人可以帮助我理解为什么会发生这种情况吗?
var
语句和函数声明语句被“提升”到其封闭范围的顶部。
因此,function global(){}
在你的函数中创建一个本地global
name.
分配给global
在你的函数内部绑定到这个本地名称。以下是如何使用提升“重写”它以了解编译器如何看待它:
function test() {
var global = function() {}; // hoisted; 'global' now local
global = true;
return false;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)