Nested Functions Losing Outer 'this'
What you'll learn: Why defining a regular function inside a method causes you to lose access to the outer method's this context.
The Problem with Nested Function Declarations
When you declare a regular function inside a method, that inner function gets its own this binding based on how it's called. It doesn't automatically inherit the outer method's this — it creates a completely new context.
const team = {
name: "Developers",
members: ["Alice", "Bob"],
showMembers() {
console.log(this.name); // "Developers" ✓
this.members.forEach(function(member) {
// This inner function has its own 'this'!
console.log(this.name); // undefined (strict) or global (non-strict)
console.log(member + " is on " + this.name); // Won't work!
});
}
};
team.showMembers();
// "Developers"
// undefined
// undefined
Why This Happens
Remember: this is determined by the call-site, not where the function is written. The callback function inside forEach is called by forEach itself, not as a method on team. So it loses the outer context completely.
Common Workarounds
You've learned several solutions already:
- Use
bind()on the inner function - Use
call()orapply()to invoke it with the right context - Use arrow functions (which don't create their own
this) - Store the outer
thisin a variable likeconst self = this
// The self/that pattern (old but reliable)
showMembers() {
const self = this;
this.members.forEach(function(member) {
console.log(member + " is on " + self.name); // Works!
});
}
Key Takeaway: Regular function declarations always create their own this binding, even when nested inside methods. The inner function doesn't "see" the outer this — you must explicitly preserve or pass it.