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
thischanges based on the
contextin which the
thisrefers 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.
thisinside global context
this inside a function
this inside constructor function
this inside a function inside an object
this inside an inner function
this inside a function and
strict mode is on.
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.
thisinside an arrow function — in this example, the parent scope of the
this inside an inner function as an arrow function. Case 1. When arrow function is inside an normal function.
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
this manually by using JS inbuilt methods
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
For further explanation: