← Lessons

quiz vs the machine

Gold1400

Frontend

The this Binding Rules

How JavaScript decides what this points to at call time.

5 min read · core · beat Gold to climb

this is set by the call

In a regular function, this is not fixed by where the function is written. It is decided by how the function is called, which surprises many developers.

The four rules

  • Default binding applies to a plain call. this is the global object, or undefined in strict mode.
  • Implicit binding applies when called as a method. this is the object before the dot.
  • Explicit binding uses call, apply, or bind to set this by hand.
  • New binding with the new keyword makes this a freshly created object.

Precedence

When rules compete, the order is new, then explicit, then implicit, then default. A bound function wins over an implicit method call, which is why bind is reliable for callbacks.

Arrow functions are different

An arrow function has no own this. It captures this from the enclosing lexical scope at definition time and ignores all four call rules. This makes arrows ideal for callbacks inside a method that need the surrounding this.

A common trap

Passing a method as a callback detaches it from its object, so implicit binding is lost and this becomes the default. Bind it or wrap it in an arrow to keep the intended this.

Key idea

For regular functions this depends on the call site by four ranked rules; arrows ignore them and capture this lexically.

Check yourself

Answer to earn rating on the learn ladder.

1. What decides this inside a regular function?

2. How does an arrow function handle this?