Kheerganga Top, Himanchal

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 referring to.

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

So first let’s see what refers to? 🤔

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

Lets understand this by an example:

In the above code, we are using at two different places and the value of 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. inside global context
this inside a global js file always points to window object.

2. inside a function

this inside a function points to window object.

3. inside constructor function

this inside a constructor function points to the contructor keys.

4. inside a function inside an object

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

5. inside an inner function

this inside an inner function points to the window object.

6. inside a function and 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. inside an arrow function works differently.

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

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

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

3. 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 of manually by using JS inbuilt methods and . For this article it will be too much to explain these. But for the demonstration purpose I am showing how can we change the of this using :

For further explanation:

Practice Questions:

A passionate iOS Developer since 2014.