The this Keyword
The problem
A method often needs to refer to the object it was called on, without hardcoding that object's name — this gives every function a way to refer to 'whatever I was called on,' but that binding is determined by how a function is called, not where it's defined, which is a frequent source of confusion.
Why now
Prototypes and inheritance already established that methods are shared across objects via the prototype chain; this is the mechanism that lets one shared method still know which specific object it's currently operating on — and execution-context-and-hoisting already established that context is set up freshly for each call, which is exactly when this gets bound.
Mental model
this is not fixed by where a function is written — it's determined by how it's called: obj.method() binds this to obj, a bare function call binds this to undefined (in strict mode) or the global object, and arrow functions deliberately opt out entirely, inheriting this from their enclosing scope instead of getting their own.
Requires
- Prototypes & InheritanceJavaScript Runtime
this exists specifically to let a method shared via the prototype chain still operate on the correct specific instance; without shared methods via prototypes, the problem this solves doesn't arise.
- Execution Context & HoistingJavaScript Runtime
this is bound fresh as part of setting up a function's execution context at call time — you need the execution-context model to explain why this can differ across calls to the exact same function.
Used in
- Every object method definition relying on this to access its own instance's data
- Event handlers, where losing the correct this binding is one of the most common JavaScript bugs
- call/apply/bind, which exist specifically to control this explicitly
- Arrow functions' popularity in class methods and callbacks specifically to avoid this-binding bugs
Projects
- Write a method that loses its this binding when passed as a callback (e.g. to setTimeout), diagnose why, then fix it three ways: bind(), an arrow function, and an explicit closure variable
- Predict the value of this in five different call-site scenarios (method call, bare call, arrow function, bind, event handler) before running the code
Examples
- const fn = obj.method; fn(); loses this — the method is now called bare, detached from obj
- Arrow functions used as class methods automatically capture the surrounding this, sidestepping the detachment problem entirely
Resources
- MDN — thisdocs
Mastery checklist
- I can predict the value of this for a method call, a bare function call, and an arrow function
- I can explain why passing a method as a callback can lose its this binding
- I can use bind, call, or apply to control this explicitly
- I can explain why arrow functions are often preferred for callbacks that need the enclosing this