Course contentsShow
← TypeScript
Lesson 280 of 1,7966. FunctionsFree lesson

The Problem: Losing this in JavaScript

Why methods passed as callbacks lose their this binding and how it causes runtime errors.

The Problem: Losing this in JavaScript

What you'll learn: Why methods passed as callbacks mysteriously fail when accessed later, and how losing this causes runtime errors.

The Root Cause

In JavaScript, the value of this inside a method depends on how the function is called, not where it's defined. When you pass a method as a callback to another function (like event handlers, setTimeout, or array methods), you're passing the function itself without its object context. The function gets called later in a different context, and this points to something unexpected—or undefined in strict mode.

Think of it like giving someone your house key without telling them your address. The key (method) is useless without knowing which house (object) it belongs to.

The Classic Mistake

class Counter {
  count: number = 0;

  increment(): void {
    this.count++;
    console.log(this.count);
  }
}

const counter = new Counter();

// Direct call works fine
counter.increment(); // 1

// Passing as callback loses `this`
setTimeout(counter.increment, 1000);
// Runtime error: Cannot read property 'count' of undefined

When setTimeout calls counter.increment, it doesn't know about counter. It just invokes the function, so this becomes undefined (in strict mode) or the global object.

Why This Matters

This issue appears constantly with:

  • Event listeners: button.addEventListener('click', counter.increment)
  • Array methods: numbers.forEach(counter.increment)
  • Async callbacks: fetch(url).then(counter.increment)

Key Takeaway: Methods lose their this binding when passed as callbacks because JavaScript determines this at call time, not definition time—leading to runtime errors when the method tries to access instance properties.