DEV Community

samsssagar
samsssagar

Posted on • Updated on

What the hell is "this"?

If you're reading this post, then probably I will assume that you know there are a lot of nuances in JavaScript. The nuances of JavaScript are what make it such a powerful language. this keyword is one such nuance.

The Prologue

Assume that you are a 5 years old kid. And start imagining with me.

Imagine you are in a room with a bunch of other people. You want to talk to one specific person, but you don't know their name. You can say "Hello!", but the other people in the room might not know who you are talking to. However, if you say "Hello, [person's name]!", the other people in the room will know who you are talking to.

The "this" keyword is like the person's name in this analogy. It tells the JavaScript engine who you are talking to.

Imagination Over!!!

Act Two

Now, let's understand this w.r.t. Execution Context. "this" always refers to the object that is currently executing the code.

Let's see some examples:

Example 1

console log example

Output Window object

If you will log "this", the output which you see is window object. Why? Because, the object which is currently executing the code is Window Object.

Still confused??

Now remember the Act One analogy. In the case of the console.log(this) command, you are talking to the window object. Therefore, the this keyword refers to the window object.

Example 2

Basic Object example

Output - Clark Kent is Superman

If you observe here, the current object that is executing in code is superhero and that's why the name and alias is referring to superhero object's properties. The function message() was called in context of superhero object.

Example 3

Function related example

Output

Function related example output

In this example, if you observe, on line number 10 we are calling outer() function. Now, What is the object which is executing the outer() function. The answer is Window Object.

That's why if you see the output, Window object is getting printed in the console log of outer() function. Now, you might be thinking why the console log inside the inner() function prints Window Object.

Now, again remember the Act One analogy.
The this keyword is like the person's name in this example. It tells the JavaScript engine who you are talking to. In the case of the inner() function, you are talking to the outer() function. Therefore, the this keyword refers to the outer() function.

Climax

If you remember the analogy given in the prologue section, the this concept will be very much clear. I will be posting more blogs about the basics concepts of JavaScript and gradually, I will move to the more advanced concepts.

I hope this blog post has been helpful. If you have any questions, please feel free to leave a comment below.

Thanks for reading!

Top comments (0)