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) }
}
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
thisis used alone, i.e outside any function (in the global context), it will refer to thewindowobject (if JS is running in a browser), andglobalobject (if JS is running in Nodejs).If
thisis used inside a regular function, it will again refer to thewindow/globalobject. But in strict mode (I will post on what strict mode is some other day), JavaScript bindsthisto undefined.If
thisis used inside a method of an object, it will refer to the object, that particular method is a property of.If
thisis used inside a constructor function, and when thenewoperator is used, JS binds thethiskeyword with the newly created object by that constructor. Hence, it will refer to a new object that is created.In arrow functions, JS sets
thislexically. It means the arrow function does not create its own execution context but inheritsthisfrom 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 :)
Top comments (0)