Why does the DOM have an object called self
and another called window
when they are the same thing? To add to the confusion window
has a property called 开发者_如何学编程self
so:
window === window.self === self
Why is it like this? Which one should I use?
self
is defined by the javascript environment and points to the [global] object (but is not part of the spec, so might not be there), while window
is part of the DOM specification.
In most browsers the window
is used as the [global] object, but this is not always so.
That self == window.self
is not strange as they are the same object - when self
is being looked up, it is found as a property of the global object (window
). So it is in fact the same as window.self == window.self
.
As noted elsewhere, to reliable reference the [global]
object, you should define it your sef by running var global = this;
in the global execution context.
When you're calling self
it is window.self
, so same thing there like any other global property (e.g. location
is really window.location
).
The reason it's there? Usually for checks like this:
if(window.top != window.self) {
alert("We're in a frame");
}
The global self
is a shortcut to window.self
. They are both the very same object.
As to why there are both window
and self
, in a web page context, self
is always equal to window
(as far as I know). But I guess this doesn't have to always be that way - Javascript/ECMAScript is not limited to use in a web page where there is a DOM.
As to what to use, both should be safe to use in a normal web page context AFAIK. See @Nick's comment for good arguments for using window
, though.
精彩评论