Michael Theriot Michael Theriot - 3 months ago 13
Javascript Question

Global variables undefined when referencing them via window object

I'm fairly new to declaring variables globally via window, so I was a bit surprised that the following snippet behaves differently depending on the browser.

window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);‚Äč


Firefox, IE, Opera


Good

undefined

Good


Chrome and Safari


Good

Good

Good


My initial belief was that it should behave the way Chrome and Safari does, but I realize I might not have a proper understanding of the window object, so would anyone more knowledgeable explain this?

I realize I can just use
var test = "Good";
for that scope, but I'm interested in why the browsers handle it differently.

http://jsfiddle.net/WHYFc/

Answer

Your JSFiddle is using window.load to create the script.

document.write after load CLEARS/WIPES the document so what you are seeing is normal for those browsers and webkit simply is more lenient

Here is the code you produce in jsfiddle:

window.addEvent('load', function() {
window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);
});

Change your fiddle to head or body and it will work as expected

DEMO