This Keyword in JavaScript
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 thecontext
in which themethod
is beingcalled
.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.
this
inside global context
2. this
inside a function
3. this
inside constructor function
4. this
inside a function inside an object
5. this
inside an inner function
6. 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.
this
inside an arrow function — in this example, the parent scope of thesample
method iswindow
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/