Javascript window.onload scope

Can someone explain why the warning is returning "undefined" instead of "hello"?

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

      

+2


a source to share


2 answers


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

To be globally accessible, and in particular to be a a

member of an object window

, modify your code as follows:

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

      



Or this way:

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

      

+5


a source


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

a is bound to the anonymous function you assigned to load.

you CAN add as a window member if you want:



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

      

but I suggest not to.

+5


a source







All Articles