Confusion: Nested Functions
You'll learn why this inside a nested function unexpectedly loses its connection to the outer function's context.
The Unexpected Context Loss
When you define a function inside another function, you might expect the inner function to inherit the outer function's this value—but it doesn't. Each function gets its own this binding determined by how that function is called, not where it's written.
This catches many developers off guard because it behaves differently from lexical scope (where inner functions do access outer variables). The this keyword follows dynamic binding rules, resetting with each function call.
Why It Happens
const person = {
name: 'Alice',
hobbies: ['reading', 'coding'],
showHobbies: function() {
console.log(this.name + ' likes:'); // 'this' is person
this.hobbies.forEach(function(hobby) {
console.log(this.name + ' enjoys ' + hobby);
// 'this' is now undefined (strict mode) or global!
});
}
};
person.showHobbies();
// Alice likes:
// undefined enjoys reading
// undefined enjoys coding
The nested function inside forEach is called as a regular function (not as a method), so its this doesn't refer to person. It's a completely new function call with its own binding.
The Mental Model
Think of this like a name tag that gets handed out at the door of each function. Just because you walked through one door with a "Manager" tag doesn't mean the next door automatically gives you the same tag. Each function call issues its own this tag based on how it was invoked.
Key Takeaway: Nested functions don't inherit this from their outer function—each function call establishes its own this binding independently, creating confusion when you expect closure-like behavior.