DEV Community

Shrushti Polekar
Shrushti Polekar

Posted on

More About ‘this’ Keyword in JavaScript

Image description
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:

  1. Global Object
  2. ‘this’ keyword Image description Suppose if we create a user object with some properties and methods, Image description on calling the login function , we can see that the this keyword is nothing but user object! Image description Now suppose we attach any new method on user, and call it , Image description Image description hen 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 ,
Image description
on calling the function we can see that the this keyword points to global object.
Image description
But that’s not the case with constructor function.

Lets see this constructor function f2,
Image description
Now if create an object of f2 and log it to the console we get,Image description
Image description
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,
Image description
Image description
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.
Image description
Before arrow function, this was done by using bind function,
Image description
Image description
This was all about ‘this’ keyword!!!

Hope it helps!

Happy learning!

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Thanks for sharing your perspective on the topic.