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

Common Patterns: Method References

Fixing lost 'this' when passing object methods as callbacks using bind().

Common Patterns: Method References

What you'll learn: How to safely pass object methods as callbacks without losing their this context using bind().

The Problem: Methods as Values

When you pass an object method as a callback (to setTimeout, an event listener, or array methods like map), you're extracting the method from its object. This breaks the implicit binding—the function no longer knows what this should be.

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

// Direct call works fine
user.greet(); // "Hello, Alice"

// But passing as callback loses 'this'
setTimeout(user.greet, 1000); // "Hello, undefined" (strict mode error)

The Solution: Bind Before Passing

Use bind() to create a permanently-bound version of the method before passing it as a callback:

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

// Bind creates a new function with 'this' locked to user
setTimeout(user.greet.bind(user), 1000); // "Hello, Alice" ✓

Real-World Pattern

This pattern appears constantly with event handlers and array methods:

const counter = {
  count: 0,
  increment() {
    this.count++;
    console.log(this.count);
  }
};

// Array.forEach expects a callback
[1, 2, 3].forEach(counter.increment.bind(counter));
// Logs: 1, 2, 3

Key Takeaway: When passing object methods as callbacks, use .bind(objectName) to preserve the this reference—the method becomes a "bound function" that always knows its context.