Course contentsShow
← JavaScript
Lesson 581 of 2,72314. The 'this' KeywordFree lesson

Event Handlers and 'this'

How event listeners change 'this' to the event target, breaking expected method behavior.

Event Handlers and 'this'

You'll learn: Why event handlers cause this to point somewhere unexpected, breaking your object methods.

The Event Handler Trap

When you attach a method as an event listener, the browser rebinds this to the DOM element that triggered the event—not your original object. This is a common source of bugs because your method suddenly can't access its own object's properties.

Think of it like lending your employee ID badge to the front desk. When someone uses your badge, the building's security system thinks they are you. Similarly, when the browser calls your method, it makes this refer to the event target (like a button), not your object.

The Problem in Action

const player = {
  score: 0,
  handleClick() {
    console.log(this); // Logs the button, NOT player!
    this.score++;      // Error: button has no 'score'
  }
};

button.addEventListener('click', player.handleClick);

When the button is clicked, this inside handleClick refers to button—the event target—because that's the implicit binding rule for event handlers. The browser essentially calls button.handleClick().

Why This Happens

Event listeners use implicit binding. The browser calls your function like this behind the scenes: eventTarget.yourFunction(). The call-site determines this, and the call-site here is the DOM element.

This breaks expected method behavior because you wrote handleClick expecting this to be player, but the browser changed it.

Key Takeaway: Event handlers rebind this to the event target (the DOM element), not the object where the method was defined—you must use bind(), arrow functions, or wrapper functions to preserve the correct context.