What's the difference between self and window?
I have a JavaScript that deals with with detection whether the page is in frames or not. I used top.frames[] etc. and everything works fine.
In this script I noticed that I can use "window" or "self" interchangeably and everything still works. Is "window" same as "self" when used in HTML page?
self
is a read-only property that can be more flexible than, and sometimes used in favor of, the window
directly. This is because self
's reference changes depending on the operating context (unlike window.self
, which only exists if window
exists). It's also great for comparisons, as others have mentioned.
For example, if you use self
inside a Web Worker (which lives in its own background thread), self
will actually reference WorkerGlobalScope.self
. However, if you use self
in a normal browser context, self
will simply return a reference to Window.self
(the one that has document
, addEventListener()
, and all the other stuff you're used to seeing).
TL;DR while the .self
in window.self
will not exist if window
doesn't exist, using self
on its own will point to Window.self
in a traditional window/browser context, or WorkerGlobalScope.self
in a web worker context.
As usual, MDN has a great writeup on this subject in their JavaScript docs. :)
Side note: The usage of self
here should not be confused with the common JS pattern of declaring a local variable: var self = this
to maintain a reference to a context after switching.
You can read more about that here: Getting Out of Binding Situations in JavaScript.
From Javascript: The Definitive Guide:
The Window object defines a number of properties and methods that allow you to manipulate the web browser window. It also defines properties that refer to other important objects, such as the
document
property for the Document object. Finally, the Window object has two self-referential properties,window
andself
. You can use either global variable to refer directly to the Window object.
In short, both window
and self
are references to the Window object, which is the global object of client-side javascript.
Here's the explanation and example from the MDN page for window.self
:
if (window.parent.frames[0] != window.self) {
// this window is not the first frame in the list
}
window.self is almost always used in comparisons like in the example above, which finds out if the current window is the first subframe in the parent frameset.
Given that nobody is using framesets these days, I think it's okay to consider that there are no useful cases for self
. Also, at least in Firefox, testing against window
instead of window.self
is equivalent.
window
and self
both refer to the global object of the current web page.
For more info have a look at http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific