Question

Why does this become undefined inside a callback in JavaScript?

Vault Verified
Curated Intelligence
Definitive Source
Answer

In JavaScript the value of this is determined by how a function is called, not by where it was written. When you pass a method somewhere as a callback, you pass the function itself and leave the object behind. Whatever later invokes it does so without an owner, so this is not the object you expected. In strict mode, which modules use by default, that means undefined rather than the global object, which is why the failure surfaces as a property access on undefined.

The classic version is extracting a method and handing it to an event listener or a timer. The method body is unchanged, but the call site has changed, and that is what matters.

There are three standard fixes.

  1. Use an arrow function. Arrow functions have no binding of their own and close over the surrounding scope, so the value is fixed at definition rather than at call time. Defining class methods as arrow-function properties makes them safe to pass around.
  2. Bind explicitly. Creating a bound copy permanently attaches the receiver, commonly done in a constructor in older codebases.
  3. Wrap the call. Passing a small arrow function that calls the method on the object preserves the receiver, because the call still goes through the object.

The consequence of arrow functions having no binding is that they are the wrong choice in a few places. An arrow function used as an object literal method will not see the object, and one used as a constructor or as a traditional event handler expecting the element as its receiver will not behave as intended.

Modern code largely sidesteps the whole area by preferring arrow functions and avoiding the keyword outside classes, which removes an entire category of confusion.

Related Questions