首先,让我们看一下代码。
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
var b=1;
}
run();
我认为结果是。01
但实际上,结果是0undefined
。
然后我修改这段代码。
var a=0;
b=1;
document.write(a);
function run(){
document.write(this.b); //or document.write(window.b)
var b=1;
}
run();
是的,这次它按预期运行。01
. 我无法理解,为什么?
更有趣的是,我再次修改了代码。
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
//var b=1; //I comment this line
}
run();
结果是 01。
那么,有人可以解释一下吗?
感谢您分享您的观点。我简化了这段代码
b=1;
function run(){
console.log(b); //1
}
二:
b=1;
function run(){
var b=2;
console.log(b); //2
}
三:
b=1;
function run(){
console.log(b); //undefined
var b=2;
}