谁能解释一下(全局范围内的代码)
var a = a || 4 // a exists & is 4
window.a = window.a || 4 // a exists & is 4
window.a = a || 4 // a is undefined error
a = a || 4 // a is undefined error
解释这 4 项作业之间的区别,以及为什么有些作业能够正确处理而其他作业却不能。
[编辑]此特定示例在 V8 Chrome 控制台上进行了测试。
最佳答案
var a = a || 4 // var a is evaluated at compile time, so a is undefined here
window.a = window.a || 4 // window.a is simply undefined
window.a = a || 4 // no var a, therefore the variable doesn't exist, = reference error
a = a || 4 // again, no var, reference error
var
语句在最接近的封装范围中声明变量/函数,并将其设置为 undefined
。当没有 var
时,就根本没有声明变量/函数。因此引用错误。
一些例子。
函数
语句:
foo(); // works
function foo() {}
bar(); // TypeError: undefined is not a function
var bar = function(){};
var
语句:
function test(foo) {
if (foo) {
var bar = 0; // defined at compile time in the scope of function test
} else {
bar = 4; // sets the bar above, not the global bar
}
return bar;
}
console.log(test(false)); // 4
console.log(bar); // ReferenceError
关于Javascript 将全局变量分配给自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4409897/