More About ‘this’ Keyword in JavaScript
Whenever any code is executed in JavaScript, it runs inside an Execution Context. The Global Execution Context is the very first Execution Context on the the call stack. The first thing JS Engine does is, it creates Global Execution Context and gives you two things:
- Global Object
- ‘this’ keyword
Suppose if we create a user object with some properties and methods,
on calling the login function , we can see that the this keyword is nothing but user object!
Now suppose we attach any new method on user, and call it ,
Then also the this keyword points to user object!
Thus , the ‘this’ keyword is nothing but the object that the function is a property of!
Now suppose we have a regular function ,
on calling the function we can see that the this keyword points to global object.
But that’s not the case with constructor function.
Lets see this constructor function f2,
Now if create an object of f2 and log it to the console we get,
Thus we can say that , when dealing with regular functions ,the ‘this’ keyword points to the global object. But in case of constructor function ,it will point to that respective object itself.
Now see the below object obj1,
since the ‘anotherfunction’ is not really associated with obj1(it behaves like a regular function)directly, the ‘this’ keyword inside it points to global object.
so in this case , how can we make that ‘this’ ,point to obj1?
Well this can be achieved by arrow functions.
Before arrow function, this was done by using bind function,
This was all about ‘this’ keyword!!!
Hope it helps!
Happy learning!