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
thiswhen 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.