JavaScript 'this' illustrated: Learn it once and for all!

kokaneka

kapeel kokane

Posted on August 14, 2021

JavaScript 'this' illustrated: Learn it once and for all!

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();
Enter fullscreen mode Exit fullscreen mode

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:
this is JavaScript

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:

js illustrated book

💖 💪 🙅 🚩
kokaneka
kapeel kokane

Posted on August 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related