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?
The window object is not part of the DOM.
window is the execution context and global object for that context's JavaScript. document contains the DOM, initialized by parsing HTML. screen describes the physical display's full screen.
The window object represents the browser window. The document object represents the HTML document loaded in that window. The window object has many useful properties like the location object and the setTimeout function.
Window Vs Document Window object : It is the top most object and outermost element of the object hierarchy as shown in Figure 1. The window object represents a window/tab containing a DOM document where as document object is property of window object that points to the DOM document loaded in that window.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With