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

Callbacks and Lost Context

Learn why passing methods as callbacks often loses their 'this' binding and how to identify the issue.

Callbacks and Lost Context

You'll learn: Why passing an object's method as a callback often makes it forget its object — and how to spot this frustrating bug.

The Callback Problem

When you pass a method as a callback, JavaScript doesn't pass the method attached to its object — it passes the function alone. The calling code invokes it as a standalone function, so this gets bound by whatever context that code uses (usually undefined in strict mode or the global object).

Think of it like ripping a page out of a book and handing it to someone. They can read the text, but they've lost the context of which book it came from.

How It Happens

const user = {
  name: "Alice",
  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

user.greet(); // "Hello, I'm Alice" ✅

setTimeout(user.greet, 1000); // "Hello, I'm undefined" ❌

When you call user.greet(), this is user (implicit binding). But setTimeout(user.greet, 1000) passes just the function to setTimeout. Inside setTimeout, it's called as a plain function — no object in sight.

Spotting the Issue

Look for patterns where methods are:

  • Passed to setTimeout, setInterval, or event listeners
  • Given to array methods like forEach
  • Handed to any function that calls them later

If you see a method passed without being called immediately with its object, context is probably lost.

Key Takeaway: Callbacks disconnect methods from their objects. Passing obj.method as a callback loses the this binding because the function is invoked later without reference to obj.