简体   繁体   中英

javascript window.onload scope

Can someone explain why the alert returns "undefined" instead of "hello"?

window.onload = function() {  
    var a = 'hello';  
    alert(window.a);  
}

variable 'a' is not part of window in your context.

a is scoped to the anonymous function you've assigned to onload.

you COULD add a as a member of window if you wanted:

window.onload = function() {  
    window.a = 'hello';  
    alert(window.a);  
}

but i'd suggest against doing so.

"Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope." - ( source )

To be accessible globally, and particularly to make a a member of the window object, alter your code in this way:

var a; // defined in the global scope
window.onload = function() {  
    a = 'hello'; // initialized
    alert(window.a);  
}

Or in this way:

var b = 'world'; //defined and initialized in the global scope
window.onload = function() {  
    alert(window.b);  
}

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