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
this
is used alone, i.e outside any function (in the global context), it will refer to thewindow
object (if JS is running in a browser), andglobal
object (if JS is running in Nodejs).If
this
is used inside a regular function, it will again refer to thewindow/global
object. But in strict mode (I will post on what strict mode is some other day), JavaScript bindsthis
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 thenew
operator is used, JS binds thethis
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 inheritsthis
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 :)
Top comments (0)