What's the difference between self and window?

Milan Babuškov picture Milan Babuškov · Sep 3, 2010 · Viewed 16.5k times · Source

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?

Answer

Titus picture Titus · Apr 26, 2016

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.