5) Canvas Lesson

Understand the Different Behaviors of the JavaScript this Keyword

3 min to complete · By Ian Currie

This lesson is a quick clarifier of this, and how its value changes depending on the context from which it is called.

JavaScript This Keyword in Different Contexts

The behavior of the JavaScript this keyword varies depending on the context.

Context JavaScript this behavior
An arrow function this refers to the this of the enclosing scope
A method this refers to the object on which it is called (unless that method was defined using an arrow function)
The main script this refers to the global object, usually Window in the context of a browser
An event handler this refers to the element on which the event listener has been added. If you use an arrow function, however, it will be the this of the enclosing scope.

Learn by Doing

Experiment with this in the browser console. Try calling it from different places and see what you get.

To learn more about this, check out the following lessons from the JavaScript 101 course where this is covered in more detail in terms of the different contexts:

Summary: Understand the Different Behaviors of the JavaScript This Keyword

  • The behavior of the JavaScript this keyword varies depending on the context
  • The this keyword can be used in different contexts:
    • Arrow functions
    • Methods
    • The main script
    • Event handlers
  • For this course, you'll be fine just using this within class declarations