This in JavaScript
In JavaScript, the value of this
is dynamic and typically determined by how a function is called. This means that what affects the value of this
is not when it’s declared, but where it’s invoked.
There are 5 ways to determine the value of this
:
-
In a regular function call,
this
refers to the global object (theWindow
object in browsers in non-strict mode, orundefined
in strict mode). -
When a function is called as a method of an object,
this
refers to that object. -
When a function is called with the
new
keyword, a new object is created before the function executes, andthis
refers to this newly created object. -
We can also use the
apply
,call
, andbind
methods to explicitly specify which objectthis
should refer to. -
Arrow functions, introduced in ES6, don’t have their own
this
value. Instead, they inheritthis
from the nearest outer function. If that outer function is also an arrow function, it will continue looking up the scope chain. This process continues until it finds the defaultthis
value in the global environment (e.g.,window
in browsers).