JavaScript this Keyword

The “this” keyword in JavaScript can be a source of confusion for developers. In this article, we’ll try to understand this keyword in different contexts.

Global Context

If the this keyword is used in the global context (outside any function), it’ll always refer to the global object, which is the window object in the browser and the global object in Node.

console.log(this === window); // true

This is always true whether we’re using ‘strict mode’ or not.

Function Context

In a simple function (not a method), this refers to the global object if we’re not using ‘strict mode’

function show() {
console.log(this === window); // true
}

show();

And if we are using ‘strict mode’ it’ll be undefined.

"use strict";

function show() {
  console.log(this === undefined);
}

show();

Note that arrow functions don’t get their own this keyword. Instead, they use their parent scope’s this keyword.

Method Context

In a method, this keyword refers to the object that is calling the method.

let car = {
  brand: 'Lexus',
  getBrand: function () {
    return this.brand;
  }
}

console.log(car.getBrand()); // Lexus

Note that it’s not important in which object the method was defined. The only important thing is that which object is calling the method. For instance, here we define the method in one object and then borrow that method for another object.

let lexus = {
  brand: 'Lexus',
  getBrand: function () {
    console.log(this.brand);
  }
}

let toyota = {
  brand: 'Toyota'
}

toyota.getBrand = lexus.getBrand //method borrowing

toyota.getBrand() // Toyota 

call() and apply()

We can use call() and apply() methods to call an object’s method with another object as this

let lexus = {
  brand: 'Lexus',
  getBrand: function () {
    console.log(this.brand);
  }
}

let toyota = {
  brand: 'Toyota'
}

lexus.getBrand.call(toyota) // Toyota 

Event Handlers

In event handlers, this keyword refers to the HTML element that received the event.

btn.addEventListener('click' , function(){
   this.style.display = 'none'
})