Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the DOM have both window and self?

Tags:

javascript

dom

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?

like image 688
hekevintran Avatar asked May 09 '10 11:05

hekevintran


People also ask

Is window part of the DOM?

The window object is not part of the DOM.

What is the difference between DOM and window?

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.

Is there any difference between window and document?

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.

What is the primary difference between document and window?

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.


2 Answers

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.

like image 56
Sean Kinsey Avatar answered Sep 20 '22 16:09

Sean Kinsey


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");
}
like image 36
Nick Craver Avatar answered Sep 24 '22 16:09

Nick Craver