Reputation: 1022
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.
Upvotes: 8
Views: 10878
Reputation: 178403
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
Upvotes: 2
Reputation: 737
If you want to store something globally even though you're opening new documents, you could (kind of ironically) use the document
object, which seems to be persistant.
document.test = "Good";
document.write(document.test); // > "Good"
document.write('<br>');
document.write(document.test); // > "Good"
document.close();
setTimeout(() => {
document.write("Also " + document.test); // > "Also Good"
document.close();
}, 2000);
Upvotes: 0