javascriptreferencewindowundefined

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/


Solution

  • Your JSFiddle is using the window load event 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 as it might look in jsfiddle:

    window.addEventListener('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