Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between this, self, window and window.self

Tags:

javascript

If I open an empty page and I run the following command in javascript console I obtain the same result:

  >>> this
  DOMWindow

  >>> self
  DOMWindow

  >>> window
  DOMWindow

  >>> window.self
  DOMWindow

What do they refer to? ...the same object or what else?

like image 422
antonjs Avatar asked Feb 09 '12 20:02

antonjs


People also ask

What is the difference between this and 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.

What is window self?

self. 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.

What is window top window self?

Definition and UsageThe self property returns the current window. The self property is read-only.


1 Answers

window is the reference to the current browser’s window the script executes in. window.self is obviously a self-reference of that within itself. And since self here is a property of the global object window, it can also be accessed as if it was a “global” variable itself: just self.

So the last three are under most circumstances indeed the same thing.

this however is completely different: it’s a variable pointing to the current scope. If you execute the following code in the console:

> var myPackage = {}
> myPackage.method = function() {console.log(this)}
> myPackage.method()

this will be pointing to the myPackage object (the scope of method).

like image 190
Arnold Avatar answered Nov 13 '22 14:11

Arnold