简体   繁体   中英

Javascript assigning global variables to themself

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 others 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM