2

我正在玩寻找东西的窗口对象。我注意到,全局窗口对象被复制到多个级别。

尝试:

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

我们有什么办法可以利用它吗?

4

4 回答 4

5

它不是真正的多级,您只需要一个属性指向自身,然后就可以进行递归。

例如:

var zombie = {
    fred: 'Hello'
};

zombie.zombie = zombie;

你现在可以疯狂地做:

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

至于为什么存在这种情况的具体细节window,请参阅 Kevin Brydons 的回答。这对于第一级是有意义的,但其余的只是自我引用的副产品。

于 2013-02-21T11:06:21.850 回答
3

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)

于 2013-02-21T11:08:13.300 回答
2

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).

Another reason is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')" - you'd have to just use "open('http://google.com/')" instead.

Yet another reason to use this property is for libraries which wish to offer OOP-versions and non-OOP versions (especially JavaScript modules). If, for example, we refer to "this.window.location.href", a JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which, could be created, for example, after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would simply refer back to "window", and also be able to get the document location without trouble. Another advantage is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, as they would not be able to do if they had hard-coded a reference to "window" (yet the default in the class could still be set as the current window object).

source

于 2013-02-21T11:08:28.480 回答
1

来自MDN

window.window :返回对当前窗口的引用。

这个简单的引用使对象循环。

于 2013-02-21T11:06:18.667 回答