DEV Community

Cover image for The This Keyword in JavaScript
Gaurav
Gaurav

Posted on

The This Keyword in JavaScript

To understand this keyword let’s take an example of the word “this” in the English language with the help of the following images.

this keyword example 1
this keyword example 2

From the above two images what I’m trying to explain is that the This keyword refers to the object it belongs to. Its value depends on where it is used.

This keyword will take the value of the owner of the function and point to the owner of the function. The value of this keyword is not static, it depends on the way the function is called.

If we'll do a simple console.log(this) in the browser, the output will be the global object(window object) which shows that the this keyword will point to the object that called the function.

A function can be called commonly in 4 ways(there are other ways):

  • As a method: In the following code example, the this keyword points to the detail object because it’s the detail object that is called the function and hence is the owner object.
'use strict'
const detail = {
  name: "samurai",
  year: "2020",
  calcAge: function () {
    return 2077 - this.year;
  },
};
detail.calcAge();//57
Enter fullscreen mode Exit fullscreen mode
  • As a simple function call in strict mode.
'use strict'
function sum() {
  let add = 2 + 2;
  console.log("sum of two numbers is" + add);
  console.log(this);
}
sum();
Enter fullscreen mode Exit fullscreen mode

For a normal function, this keyword will point to the window object but if strict mode is used then it will be undefined.

  • Arrow functions: They don't get their own this keyword. Instead, the surrounding or parent function is the one that gets pointed by the this keyword due to lexical scope.

  • As an event listener: In this case, the this keyword points to
    the handler function attached to the event.

An important point we have to remember that this keyword will not point to the function we are using it in but to the object which called the function.

Summary
1.This refers to the owner object or the object that called the function.
2.The value of this keyword depends on where it is used.
3.If 'use strict' is in the code then this will point to undefined else to the window object for a simple function call.

Top comments (0)