this Keyword in JavaScript

this Keyword in JavaScript

Introduction

this keyword is a special keyword that is created for execution purposes and can be used in a function. It takes the value of the owner of the function in which it is used however the value of this keyword is not static and doesn't remain the same everywhere. Its value depends upon how the function is called and only after calling it does the value gets assigned.

Different Ways Of Calling Functions

There are four ways in which a function can be called:

  • Method: In this case, this keyword refers to the object that is calling the method. Therefore, when we call a method this keyword inside that method points toward the object in which the method is called.
const name = {
    year: 2000,
    calcAge: function(){
    console.log(this);
    console.log(3000 - this.year);
    };
};
Harry.calcAge();
  • Calling Functions Normally: In this case, this keyword is undefined but that is only valid for strict mode. So, if you're using this alone then it refers to a global object because it is running in the global scope.
let x = this;
document.getElementById("demo").innerHTML = x;
  • Event Handlers: In this case, if a function is called an event listener then this keyword will point to the DOM element to which the handler function is attached.

a) Case 1: If this keyword is outside any function. For eg-

console.log(this);

b) Case 2: If the parent scope of the arrow function is global. For eg-

const num = birthNum => {console.log(birthNum);console.log(this);}num(23);

c) Case 3: If you aren't using strict mode in a regular function. For eg-

const num = function (birthNum) {​console.log(birthNum);console.log(this);​};​​num(23);​
  • Arrow Functions: In this case, these functions don't have their own this keyword. However, this keyword in arrow functions would point to the keyword of the surrounding function.

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer 🤔!