The 'this' Keyword
What is 'this'?
In JavaScript, the this keyword refers to an
object. Which object it refers to depends on how it is
being invoked (used or called).
- In an object method,
thisrefers to the object. - Alone,
thisrefers to the global object (window). - In a function,
thisrefers to the global object. - In a function, in strict mode,
thisis undefined. - In an event,
thisrefers to the element that received the event.
'this' in a Method
When used in an object method, this refers to the object.
'this' Alone (Global Context)
When used alone, this refers to the global object. In a
browser window, the global object is [object Window].
Explicit Binding: call(), apply(), and bind()
The call(), apply(), and
bind() methods allow you to explicitly set the value of
this for a function call.
'this' in Arrow Functions
Arrow functions treat this differently. They don't
have their own this binding. Instead,
this is looked up in scope just like a normal
variable. This is called lexical scoping.
Summary
thisrefers to the object that is executing the current function.- The value of
thisis determined at runtime (dynamic binding), except for arrow functions. - Use
call,apply, orbindto controlthismanually. - Arrow functions inherit
thisfrom the surrounding code.
Quick Quiz
In an event handler, what does 'this' refer to?
Enjoying these tutorials?