Window.window - Web APIs 编辑

The window property of a Window object points to the window object itself. Thus, the following expressions all return the same window object:

window.window
window.window.window
window.window.window.window
// ...

In web pages, the window object is also a global object. This means:

  1. global variables of your script are in fact properties of window:
    var global = {data: 0};
    alert(global === window.global); // displays "true"
    
  2. you can access built-in properties of the window object without having to type window. prefix:
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    alert(window === window.window); // displays "true"
    

The point of having the window property refer to the object itself, was likely 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 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). For example, if 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 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 refer back to "window", and also be able to readily get the document location. 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, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Window.window' in that specification.
Living StandardNo difference from the latest snapshot HTML 5.1
HTML 5.1
The definition of 'Window.window' in that specification.
RecommendationNo difference from the HTML5
HTML5
The definition of 'Window.window' in that specification.
RecommendationFirst snapshot containing the definition of Window.window.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:55 次

字数:4421

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文