Are global variables just properties of a window object?

Whenever I see a website in a browser, a javascript instance is launched. And I can declare a global variable in the console (DevTools);

var a = 1234567890; 

This variable was declared in global scope, so I can get the value of the variable like this:

 > a 1234567890 

However, I can do it too;

 > window.a 1234567890 

Do I understand correctly that the window object is an object that contains all the global variables in the website instance in the browser? If so, to which object does the window object belong? This is a bit confusing to me;

 > window Window {top: Window, window: Window, location: Location, external:, ...} > window.window Window {top: Window, window: Window, location: Location, external:, ...} > window.window.window Window {top: Window, window: Window, location: Location, external:, ...} 

Is a window object a finite global object and does it have an object named window that references itself?

+6
source share
4 answers

Is a window object a finite global object and does it have an object named window that references itself?

Yes and yes. This, for example, returns true :

 window.window.window.window.window === window.window; 

You can, if you want, get a list of all the properties of the window object (and therefore all global variables) using Object.keys :

 console.log(Object.keys(window)); 

Note, however, that if you think too much about global variables, there may be a problem with the architecture of your code.

+12
source

Yes, the window object

Global Object (ยง15.1 ES5 Specification)

A unique global object is created before the control enters any execution context.

Unless otherwise specified, the standard built-in properties of a global object have the attributes {[[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}.

The global object does not have an internal property [[Construct]]; It is impossible to use a global object as a constructor with a new statement.

The global object does not have an internal [[Call]] property; it is not possible to call a global object as a function.

The values โ€‹โ€‹of the internal properties [[Prototype]] and [[Class]] of the global object are implementation dependent.

In addition to the properties defined in this specification, a global object may have additional properties defined by a node. This may include a property whose value is the global object itself; for example, in an HTML object model the properties of a window property of a global object are the global object itself.

+3
source

All global variables become properties of the window object.

 >>> window.somevar = 1; 1 >>> somevar 1 

And all the basic functions of JavaScript are window object methods .

+1
source

Yes, Window is the root element of the DOM (Document Object Model) hierarchy of objects.

0
source

Source: https://habr.com/ru/post/957661/


All Articles