Javascript window.onload scope
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 to share