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/
In HTML, the global scope is the window object. All global variables belong to the window object.
In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object.
window. variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. Global Variables are the variables that can be accessed from anywhere in the program.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With