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

Losing 'this' When Passing Methods

Why extracting a method from an object and calling it standalone loses the intended 'this' binding.

Losing 'this' When Passing Methods

You'll learn: Why extracting a method from an object and passing it as a callback causes this to lose its connection to the original object.


The Problem

When you pass a method as a callback or store it in a variable, JavaScript doesn't "remember" where the method came from. The method becomes just a standalone function, and this gets bound according to how it's called, not where it was defined.

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

user.greet(); // "Hello, I'm Alice" — works fine

const greetFn = user.greet;
greetFn(); // TypeError: Cannot read property 'name' of undefined

When you call user.greet(), the call-site shows user is the object invoking the method, so this is user. But when you extract greet into greetFn and call it standalone, there's no object before the dot—this becomes undefined (in strict mode) or the global object.

Why This Happens with Callbacks

This is especially common when passing methods to functions like setTimeout or event handlers:

setTimeout(user.greet, 1000); // Error after 1 second!

setTimeout receives the function itself, not the object. When it executes, it calls the function without any object context, so this is lost.

The Mental Model

Think of a method as a recipe card. When attached to an object, the object provides the ingredients (this). When you photocopy just the recipe and hand it to someone else, they don't automatically get your kitchen—they need their own ingredients or none at all.

Key Takeaway: Extracting a method from an object breaks the this binding because JavaScript determines this by the call-site, not where the function was originally written.