What is the this keyword and how does it work?
Answer
The this
keyword is an object that represents the context of an executing function. Regular functions can have their this
value changed with the methods call()
, apply()
and bind()
. Arrow functions implicitly bind this
so that it refers to the context of its lexical environment, regardless of whether or not its context is set explicitly with call()
.
Here are some common examples of how this
works:
Object literals
this
refers to the object itself inside regular functions if the object precedes the invocation of the function.
Properties set as this
do not refer to the object.
Event listeners
this
refers to the element listening to the event.
Constructors
this
refers to the newly created object.
Manual
With call()
and apply()
, this
refers to the object passed as the first argument.
Unwanted this
this
Because this
can change depending on the scope, it can have unexpected values when using regular functions.
Good to hear
In non-strict mode, global
this
is the global object (window
in browsers), while in strict mode globalthis
isundefined
.Function.prototype.call
andFunction.prototype.apply
set thethis
context of an executing function as the first argument, withcall
accepting a variadic number of arguments thereafter, andapply
accepting an array as the second argument which are fed to the function in a variadic manner.Function.prototype.bind
returns a new function that enforces thethis
context as the first argument which cannot be changed by other functions.If a function requires its
this
context to be changed based on how it is called, you must use thefunction
keyword. Use arrow functions when you wantthis
to be the surrounding (lexical) context.
Additional links
Last updated