Web Analytics

The 'this' Keyword

Advanced ~20 min read

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, this refers to the object.
  • Alone, this refers to the global object (window).
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.

'this' in a Method

When used in an object method, this refers to the object.

HTML
CSS
JS

'this' Alone (Global Context)

When used alone, this refers to the global object. In a browser window, the global object is [object Window].

HTML
CSS
JS

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.

HTML
CSS
JS

'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.

HTML
CSS
JS

Summary

  • this refers to the object that is executing the current function.
  • The value of this is determined at runtime (dynamic binding), except for arrow functions.
  • Use call, apply, or bind to control this manually.
  • Arrow functions inherit this from the surrounding code.

Quick Quiz

In an event handler, what does 'this' refer to?

A
The global window object
B
The element that received the event
C
The function itself
D
Undefined