DEV Community

SYED MAZHAR ALI RAZA
SYED MAZHAR ALI RAZA

Posted on

Calmy explaining "this" in JavaScript

The behavior of this keyword in different contexts can be very confusing for a JavaScript developer. Here is some must-know information regarding the same.

First things first, what exactly is this?

This is a keyword that references the object that is currently executing the function. In other words, This points to the object, of which the currently executed function is a property. For example:

let obj = {
    run : function() { console.log(this) }
}
Enter fullscreen mode Exit fullscreen mode

Now if you execute run method, it will return the obj object. This is because this is inside the run function which is a property of the obj object.

  • If this is used alone, i.e outside any function (in the global context), it will refer to the window object (if JS is running in a browser), and global object (if JS is running in Nodejs).

  • If this is used inside a regular function, it will again refer to the window/global object. But in strict mode (I will post on what strict mode is some other day), JavaScript binds this to undefined.

  • If this is used inside a method of an object, it will refer to the object, that particular method is a property of.

  • If this is used inside a constructor function, and when the new operator is used, JS binds the this keyword with the newly created object by that constructor. Hence, it will refer to a new object that is created.

  • In arrow functions, JS sets this lexically. It means the arrow function does not create its own execution context but inherits this from the outer function where the arrow function is defined.

Want to understand the concept in depth with more examples, do read this article on the same.

Happy coding :)

10DaysofJSfundamentals (Day 5)

Top comments (0)