Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does global "window" object has multi-level access

Tags:

javascript

I was playing around with the window object looking for something. I noticed, the global window object is duplicated into multiple levels.

Try:

console.log(window); // returns global window object
console.log(window.window); // returns global window object
console.log(window.window.window); // returns global window object
console.log(window.window.window.window); // returns global window object 
console.log(window.window.window.window.window); // returns global window object

console.log(window === window.window); // returns true
console.log(window.window.window === window.window.window.window); // returns true

window.zombie = "Zombie!";

console.log(window.zombie === window.window.zombie); // returns true

Is there any way we can make use of this?

like image 971
nairvijays Avatar asked Dec 05 '25 06:12

nairvijays


2 Answers

It's not really multi-level, you only need one property to point back to itself and you then have recursion.

For example:

var zombie = {
    fred: 'Hello'
};

zombie.zombie = zombie;

You can now go wild and do:

alert(zombie.zombie.zombie.zombie.fred);

As to the specifics of why this exists for window, see Kevin Brydons answer. It makes sense for the first level but the rest is just a by-product of self referencing.

like image 104
Lloyd Avatar answered Dec 06 '25 20:12

Lloyd


Mozilla have done a concise explanation of the .window property

https://developer.mozilla.org/en-US/docs/DOM/window.window

And excerpt :

The point of having the window property refer to the object itself was (probably) to make it easy to refer to the global object (otherwise you'd have to do a manual var window = this; assignment at the top of your script)

like image 36
Kevin Brydon Avatar answered Dec 06 '25 20:12

Kevin Brydon