Lesson 4
this & execution context
Build a practical mental model for this & execution context and use it in working JavaScript.
By the end, you will be able to…
- Explain this & execution context in your own words
- Use this & execution context in a small program
- Recognize and debug a common failure mode
Build the mental model
`this` is determined by how a function is called, not where it was defined. Calling user.greet() sets this to user; extracting the same function and calling it alone loses that binding entirely.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Losing `this` when passing a method as a callback (like an event handler) is one of the most common intermediate JavaScript bugs.
Real-world example
A class-based event handler that reads undefined instead of expected state is almost always a lost `this` binding, fixed with an arrow function or .bind().
Common mistakes
- Passing obj.method as a callback and losing its `this` binding
- Assuming arrow functions have their own `this` (they inherit it from the enclosing scope instead)
- Forgetting to .bind(this) or use an arrow function inside a class method used as a callback
Try it yourself
Challenge
Fix greetLater so it still logs the correct name after being detached from the object.
Knowledge check
What determines the value of `this` inside a regular function?
Summary
`this` depends on the call site; arrow functions inherit `this` from where they're defined instead of how they're called.