What is “this” In JS #1
Oh! before we jump to understand about “this” keyword, let’s take one step back and understand 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😊.