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?
The Window. self read-only property returns the window itself, as a WindowProxy . It can be used with dot notation on a window object (that is, window. self ) or standalone ( self ).
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
In the Window object, top references the topmost window. While self references the current window.
As others have explained, var self = this; allows code in a closure to refer back to the parent scope.
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.
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