What is “this” In JS #1

Badal Sharma
2 min readJun 27, 2021

--

Hi everyone, I have been using JavaScript for more than 3 years. But I still face some problems regarding the “this” keyword, as it is a little bit tricky. And if you are here then probably you would also be having some doubts regarding the usage of the “this” keyword. Let’s deep dive into the concepts of the “this” keyword.

Oh! before we jump to understand about “this” keyword, let’s take one step back and understand what “this” is not .

what this is not

The output of this code is 3, why is not incremented.

Doesn’t it look strange?

So let’s understand. When code executes “test.a = 3”, it is adding a in function-object of test, and “this” inside of the test is not pointing to the function-object of test.
So where “this” is pointing to then? It is pointing to the global object.

Hack of “this”

When code is not working according to us, then we try some hack to make it work(try to increment a in this case). Examples:

Output is 6. now a is incrementing. The problem is solved, but the real problem is ignored. It is working because of lexical scope.

Forcefully pointing “this” to function-object:

Output is 5. a is incrementing. With the help of call, we are forcefully pointing “this” as a function-object.

Let's take one more example:

Output is undefined. because “this” inside hello is pointing to global scope, and a is defined in the scope of test. I know this leads to more confusion.

Question is how “this” inside hello pointing to global scope? (it will be clear in next blog).

So what is this? “this” is a “runtime binding” (dynamic binding). It is based on the condition of how the function is invoked and that is called call-site.

We will look into more details on the working and usage of “this” keyword in the next blog of this series. Make sure that you read the next blog😊.

--

--

Badal Sharma
Badal Sharma

Written by Badal Sharma

I am Software Developer. You can join me for outing on weekends.

No responses yet