JavaScript Runtime5h estimated

The this Keyword

Difficulty
Importance

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

Used in

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

Mastery checklist