JavaScriptMed
JavaScript this Keyword — How this Works in Every Context
The `this` keyword refers to the object that is executing the current function. Its value is determined by HOW a function is called, not where it's defined. There are 4 main rules that determine what `this` refers to.
3 concepts·4 practice problems·Intermediate level
Key Concepts
- •this is determined at call time, not definition time
- •Rule 1: new binding - this = new instance
- •Rule 2: Explicit binding (call/apply/bind) - this = specified object
- •Rule 3: Implicit binding (obj.method()) - this = object left of dot
- •Rule 4: Default binding - this = window (or undefined in strict mode)
- •Arrow functions inherit this from enclosing scope
Topics Covered
Practice Problems
Common Mistakes to Avoid
- ×Losing this when passing methods as callbacks
- ×Using arrow functions as object methods
- ×Forgetting that this in nested functions is different
Interview Tips
- ✓Know all 4 binding rules in order of precedence
- ✓Explain why arrow functions are useful in callbacks
- ✓Be able to fix "this" issues with bind or arrow functions