antonjs
antonjs

Reputation: 14318

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

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?

Upvotes: 9

Views: 3823

Answers (3)

Pseudocode
Pseudocode

Reputation: 91

Always this keyword refers to the context that it was called in. But self and window even after changing context refers to Window itself.

// Log function
function logAll(){
    console.log("this >", this);
    console.log("self >", self);
    console.log("window >", window);
    console.log("window.self >", window.self);
    console.log("this.self >", this.self);
};

// Class Car
function Car(){
    this.self = 6;
};

// Instance of Car
var honda = new Car();
honda.self = 5;

// logAll() called in context Gloabal
logAll();

// Outputs
this > Window
self > Window 
window > Window 
window.self > Window 
this.self > Window 

// logAll() called in context honda
logAll.call(honda);

// Outputs
this > Car { self= 5 }
self > Window
window > Window
window.self > Window
this.self > 5

Here you can see this.self returns window in when called in global scope because in global scope

this = windows 
this.self = windows.self 
this.self = Windows

But while you are in the context of honda, an instance of Car:

this = honda 
this.self = honda.self 
this.self = 5

Context plays an important role in Javascript, while working with OOPs and inheritance.

Upvotes: 1

Andreas Köberle
Andreas Köberle

Reputation: 110922

this
DOMWindow

this is always the actual context a JavaScript expression was called in. So in your case its the global context, which is the window object when your run it in the browser. Note running the same in nodeJs will give you another result.

self
//DOMWindow

From the MDN Docs:

Returns an object reference to the window object.

window
// DOMWindow

Its what you have called: the window object.

window.self
//DOMWindow

Its the same as calling self above cause there your context is window. So calling window.self or just self or this.self, when you're in the global scope, is the same.

Upvotes: 2

Arnold
Arnold

Reputation: 2420

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

Upvotes: 8

Related Questions