Course contentsShow
← JavaScript
Lesson 650 of 2,72316. Object Methods and PatternsFree lesson

Losing 'this' Context

Recognize common scenarios where 'this' becomes undefined or points to the wrong object.

Losing 'this' Context

You'll learn why methods can mysteriously lose track of their object when passed around.

When you define a method inside an object, it looks like this should always point to that object. But JavaScript determines this at call time, not definition time. If you separate a method from its object—by assigning it to a variable, passing it as a callback, or extracting it in any way—the connection breaks.

Why It Happens

Think of a method like a business card with instructions: "Call me at this number." The card doesn't know who gave it to you. When someone calls that number, the context depends on how they dialed—not who originally printed the card.

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

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

const greetFn = user.greet;
greetFn(); // "Hello, I'm undefined" ✗

In the first call, this is user because we called it as user.greet(). In the second, we extracted the function into greetFn and called it standalone—now there's no object before the dot, so this becomes undefined (in strict mode) or the global object (in non-strict mode).

Common Scenarios

You'll lose context when:

  • Assigning a method to a variable
  • Passing a method as a callback
  • Using methods in event handlers or timers
  • Storing a method reference without its object

Key Takeaway: Methods lose their this binding when separated from their object because JavaScript determines this based on how a function is called, not where it's defined.