Hey There 👋🏾
In today's post I wanted to ask you all a question.
How many of you really understand the
this
keyword in JavaScript? 🤔
I myself have conducted several JavaScript interviews so far and sometimes I ask this question as a way to get things started and the kind of answers that I get are:
- It points to the
Object
(what object?) - It points to the
function
(which function?) - It points to itself (consciousness?)
Although there is a trend growing up which considers the need to use this
is JavaScript as a bad practice and suggests to move away from it.
That might be correct, but knowing about how something works is always good, whether we decide to use it or not!
So let's do it today! 🙌🏾
Let us see how the this
keyword in JavaScript really functions.
The actual answer
Well, most of the times the answer that we provide to that question is wrong, because the way the this
keyword works, differs based on where the this
keyword is being used.
And that is the key to understanding it. Break it down into scenarios and look at it from a per scenario basis.
Inside a function
Inside any function in the global
scope, the this
keyword points to the global
object in non-strict mode and is undefined
in strict mode.
As a method on an object
When invoked as a method on an object, like person.getName()
, the this
keyword refers to the object on which the method is being invoked.
When invoking with call
When the function is invoked using call, like getName.call(animal)
, the this
keyword refers to the object that is being passed to the call function.
When invoked with the new
keyword
In this case, when we are in the process of creating a new object by invoking a function with the new
keyword in front of it, like this:
let bruno = new Dog();
Then inside the Dog
function, all the this
keywords would point to the object that gets newly allocated and returned.
Here's the same explanation in an illustrated format for the visual learners reading this post:
And that's it. Those are the cases that would cover more than 95 percent of the scenarios.
Now you know how to answer that tricky question.
See you in the next one, Cheers! 🙌🏾
PS:
If you liked the illustration above, you might like my 🎊FREE🎊 ebook that I recently released which covers several other JavaScript concepts. Feel free to get a copy by clicking on the image below:
Top comments (7)
It'd be nice to mention arrow functions and
bind
.Thanks for sharing this however I think you really miss a lot of use cases. Your sketch does not cover 95% of use cases. Not even 30%.
Things you might consider to add
With which tool you made the notes?
Hey, I used excalidraw and figma. :)
Thanks @comscience
The illustration really helped put together what you wrote in the article
Thanks a lot. Glad it helped!