Explain the different ways the `this` keyword can be bound
Topics
ClosureJavaScript
Edit on GitHub
TL;DR
The this
keyword in JavaScript can be bound in several ways:
- Default binding: In non-strict mode,
this
refers to the global object (window in browsers). In strict mode,this
isundefined
. - Implicit binding: When a function is called as a method of an object,
this
refers to the object. - Explicit binding: Using
call
,apply
, orbind
methods to explicitly setthis
. - New binding: When a function is used as a constructor with the
new
keyword,this
refers to the newly created object. - Arrow functions: Arrow functions do not have their own
this
and inheritthis
from the surrounding lexical context.
Default binding
In non-strict mode, if a function is called without any context, this
refers to the global object (window in browsers). In strict mode, this
is undefined
.
Implicit binding
When a function is called as a method of an object, this
refers to the object.
Explicit binding
Using call
, apply
, or bind
methods, you can explicitly set this
.
Using call
Using apply
Using bind
New binding
When a function is used as a constructor with the new
keyword, this
refers to the newly created object.
Arrow functions
Arrow functions do not have their own this
and inherit this
from the surrounding lexical context.