DEV Community

Moreshwar Pidadi
Moreshwar Pidadi

Posted on • Updated on

this keyword in JS

As we know Execution Context (EC) consist of

  • Varaiable Enviornment
  • Scope Chain
  • this keyword

So lets explore this keyword more.

  1. "this" keyword/variable in JS.
  • this is special variable that is created for every Execution Context (EC) i.e for every function.

  • this takes value of (or points to) the owner of the function in whcih the "this" keyword is used.

  • Remember "this" is not static it depends on how the function is called, and it's value is only assigned when the function is actually called.

As we know the function can be called in 4 different ways

a. method => this = <object that is calling the method>

  • Ex:

Image description

Call to the function moreshwar.calcAge();
Enter fullscreen mode Exit fullscreen mode

Note: The value of _*this *_should / is moreshwar

  • As we can say now that this is object giving call to method.

  • So, using this we can now access the properties of an object. Accessing the properties using (this) is a way better solution.

b. Simple function call: where this = undefined

Note: its is valid only for strict mode
Enter fullscreen mode Exit fullscreen mode


Image description

  • If not strict mode this will point to Global object / Windows object. Which can then be more problamatic.

  • This is reason we should always be useing strict mode.

c. Function call using Arrow function

  • i.e ArrowFunctionName => = <this of sorounding function (lexical this)>

  • In Arrow function it does not get the "this keyword".

Image description

EventListner => this = <DOM elements that handler is attachedto>

  1. Hence, this will never points to the function, where we are using it, it would point to the object (parent object).

  2. Also "this" keyword will never point to the variable enviornment of the function.

  3. "this" keyword in Global Scope is always Windows Object, which make this keyword dynamic not static.

Top comments (0)