Can anyone explain this (code in global scope)
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
An explanation of what the difference is between these 4 assignments and why some handle it properly but o开发者_运维百科thers don't.
[Edit] this particular example was tested on the V8 Chrome console.
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
The var
statement declares the variable/function in the closest encapsulating scope and sets it to undefined
. When there's not var
, there's no variable/function declared at all. Therefore the reference error.
Some examples.
function
statement:
foo(); // works
function foo() {}
bar(); // TypeError: undefined is not a function
var bar = function(){};
var
statement:
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
精彩评论