Are global variables stored in specific object? For instance:
var test="stuff";
console.log(window.test);
console.log(document.test);
console.log(this.test);
All three of these tests result in undefined
, so is there an object that holds these variables?
I feel as though this is something stupid that I should already know, but I can't even seem to find the answer online.
Global variables are stored in the data section. Unlike the stack, the data region does not grow or shrink — storage space for globals persists for the entire run of the program.
A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node. js this is not the case.)
Because you used let rather than var , it gets stored in the declarative environment record associated with the global lexical environment object, rather than on the global object itself.
Here is a late but technical answer.
You ask
Are global variables stored in specific object?
The answer is yes; they are stored in something called, officially, the global object. This object is described in Section 15.1 of the official ECMAScript 5 Specification.
The global object is not required to have a name; but you can refer to its properties, such as String
, isNaN
, and Date
simply by using their name. Your JavaScript host environment will place other properties in the global object besides the ones required by the ECMAScript specification, such as alert
or console
. In a browser, I can write the script
alert("Hello world");
because alert
is a property of the global object.
Note that there does not have to be a way to access this global object at all, believe it or not. The cool thing, however, is that many host environments will put a property in the global object whose value is a reference to the global object itself. In most web browsers, this property is called window
. So we can write:
alert("Hello");
window.alert("Hello");
window.window.alert("Hello");
window.window.window.window.window.alert("Hello");
and you can also say:
var x = 5;
alert(this.x);
and get 5
alerted.
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