This Keyword in JavaScript

Kheerganga Top, Himanchal

this keyword is one of the most misunderstood and complex concept of JavaScript. I’ve spend years working in JavaScript and sometimes such scenarios comes where it becomes difficult to understand what is this referring to.

In this article I’ll try to explain as many as scenarios which I came across which uses the this . And may be one of the scenario may help you in understanding to concept of this more clearly.

So first let’s see what this refers to? 🤔

The nature of this is fluid. The value of this changes based on the context in which the method is being called . this refers to the context in which it is being called.

Lets understand this by an example:

In the above code, we are using this at two different places and the value of this is different at both the places, which is decided by the context on which it is being called.

Now let’s see how this behaves inside various code blocks.

  1. this inside global context
this inside a global js file always points to window object.

2. this inside a function

this inside a function points to window object.

3. this inside constructor function

this inside a constructor function points to the contructor keys.

4. this inside a function inside an object

this inside an object’s function points to the instance of the object.

5. this inside an inner function

this inside an inner function points to the window object.

6. this inside a function and strict mode is on.

this is because, when ES3 released, ECMA has concern, may be developers forgot to invoke constructor with new keyword.

In Addition to above scenarios, we have an additional concept top understand. And that is arrow functions. this inside an arrow function works differently.

Inside an arrow function, this has no scope of itself. It always points to the scope of parent.

  1. this inside an arrow function — in this example, the parent scope of the samplemethod is window
this inside an arrow function points to parent.

2. this inside an inner function as an arrow function. Case 1. When arrow function is inside an normal function.

3. this inside an inner function as an arrow function. Case 1. When arrow function is inside an arrow function.

Apart from these, we can also control the context of this manually by using JS inbuilt methods call bind and apply . For this article it will be too much to explain these. But for the demonstration purpose I am showing how can we change the context of this using call :

For further explanation:
https://youtu.be/-NnxwkJ4yIg

Practice Questions:
https://dmitripavlutin.com/javascript-this-interview-questions/

--

--