In the simplest of terms, the JavaScript keyword this refers to the object it belongs to on runtime, depending upon its call-site (where it is called).

However, understanding what it would refer to in any given context, requires a slightly deeper understanding of some relevant concepts, which will be covered in this article.

Just to start with, this can have the following values depending upon where it is accessed :

  • By defaultthis refers to the global object.
  • Inside a function : this refers to the global object. In strict mode, however, this will be undefined.
  • Inside a method : this refers to the owner object. (A method is a function that belongs inside an object. In other words, it’s a function that’s an object’s property.)
  • In an eventthis refers to the element on which the event was triggered.
  • Inside an Immediately Invoked Function Expression (IIFE) : this refers to the global object. In strict mode,this will be undefined, just like any other function in a global context.
  • Inside a Fat-Arrow function: When a fat arrow ()=> is used to define a function, it doesn’t create a new value for this, instead, it keeps referring to the same object it was referring to outside of the function.

This article hopes to give you an understanding of how these values are assigned to this, and how this knowledge can be utilized to suit our requirements.

#coding #javascript

How Well Do You Know “This” in JavaScript?
1.10 GEEK