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

When Lexical Binding Matters

Scenarios where lexical scope (closures, outer variables) is the right tool instead of 'this'.

When Lexical Binding Matters

You'll learn when to reach for closures and lexical scope instead of relying on this.

You've seen that this uses dynamic binding—its value depends on how a function is called. But sometimes you don't want that flexibility; you want certainty. That's when lexical binding (closures capturing outer variables) becomes the right tool.

When this Creates Problems

If you pass a method as a callback, this can lose its original context:

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

setTimeout(counter.increment, 100); // loses 'this' context

The increment method gets called later without counter as context, so this won't refer to the counter object anymore.

Lexical Binding to the Rescue

When you need a stable reference, capture it in a closure:

const counter = {
  count: 0,
  increment: function() {
    this.count++;
  },
  scheduleIncrement: function() {
    const self = this; // capture in lexical scope
    setTimeout(function() {
      self.count++; // uses captured variable, not 'this'
    }, 100);
  }
};

counter.scheduleIncrement(); // works reliably

Here, self is a lexically-scoped variable that always refers to the same object, regardless of how the inner function is called.

The Rule of Thumb

  • Use this when you want dynamic behavior—different contexts for the same function
  • Use closures when you need a fixed, predictable reference that survives being passed around as a callback

Lexical scope gives you certainty; this gives you flexibility. Choose based on whether you want the binding determined at write time (lexical) or call time (dynamic).

Key Takeaway: When callbacks or detached methods threaten to lose context, lexical variables captured in closures provide stable, predictable references that this cannot guarantee.