← Lessons

quiz vs the machine

Gold1360

Frontend

This Binding Rules

The value of this is decided by how a function is called, with arrow functions as the exception.

5 min read · core · beat Gold to climb

Call site decides this

In a normal function, this is not fixed at definition. It is set fresh on every call based on how the function is invoked. Four rules cover most cases, checked in order of priority.

  • New binding: calling with new makes this the new object.
  • Explicit binding: call, apply, or bind set this directly.
  • Implicit binding: calling as a method sets this to the object before the dot.
  • Default binding: a plain call gives undefined in strict mode or the global object otherwise.

Arrow functions are different

Arrow functions have no own this. They capture this from the surrounding scope at definition time, which makes them ideal for callbacks inside methods.

  • Passing a method as a callback loses its implicit binding.
  • bind creates a new function with this locked in.
  • Arrows ignore new, call, and apply for the value of this.

The common bug is a method reference detached from its object, leaving this undefined. Reach for bind or an arrow to keep the intended receiver.

Key idea

For normal functions the call site sets this by the four rules, but arrow functions inherit this lexically and cannot be rebound.

Check yourself

Answer to earn rating on the learn ladder.

1. What sets the value of this in a normal function?

2. How do arrow functions handle this?

3. What is the effect of bind on a function?