Posted by : at

Category : javascript

What is the use of “this” Keyword ?

1. Global Object

Open up your Chrome or Mozilla Developer Console and type this:

console.log(this);

what do you get ?

// Window {...}

The window object ! That’s because in the global scope, this refers to the global object. In a browser, the global object is the window object.

lets look at it more depth. In your console, create a new variable and assign it to your name:

var myName = 'Sujay';

We can access this new variable again by calling it:

myname  
// returns -> 'Sujay' 

Every variable you declare in the global scope is attached to the window object.

window.myName 
// return  -> 'Sujay'

window.myName === myName
//return -> true

2. Declared Object

function test(){
  return this;
}
test()

When this is used inside of a declared object, it defaults to the global(window) object. The value of this is set to the closest parent object the method is called on.

For example :

var person = {
   first_name: 'Sujay',
   last_name: 'Kundu',
   full_name: function (){
    
     console.log(this.first_name + ' ' + this.last_name);
    
   } 
};

person.full_name();
// logs => 'Sujay Kundu'

Infact this is in fact referencing the person object. So if we do something like this:

var person = {
   first_name: 'Sujay',
   last_name: 'Kundu',
   full_name: function (){
    
     console.log(this);
    
   } 
};

person.full_name();
// logs => Object {first_name: "Sujay", last_name: "Kundu", full_name: function}

As you’ll see, the console returns the person object, proving this has taken the value of person

And what would happen if this is used, where we have nested objects ?

var person = {
   first_name: 'Sujay',
   last_name: 'Kundu',
   full_name: function (){
    
     console.log(this.first_name + ' ' + this.last_name);
    
   }, 
   personTwo: {
     first_name: 'John',
     last_name: 'Doe',
     full_name: function(){
         console.log(this.first_name + ' ' + this.last_name);
     }
   }
};

person.full_name();
// logs => 'Sujay Kundu'

person.personTwo.full_name();
// logs => 'John Doe'

3. The New Keyword

When the new keyword is used(a constructor), this is bound to the new object being created.

function Car(make, model){
   this.make = make;
   this.model = model;
};

Above, you might guess that this is bound to the global object — and you’d be correct…until we add in the keyword new . When we use new the value of this is set to an empty object, in this case, myCar.

var myCar = new Car('Ford', 'Escape');

console.log(myCar);
// logs => Car {make: "Ford", model: "Escape"}

4. Using call(),bind() and apply()

We can set the value of this explicitly with call(), bind(), and apply()

5. Using Arrow Functions

Arrow Functions don’t bind this — instead this is bound lexically (i.e. based on the original context)