Question 16 / 31

What happens to this when a method is passed to setTimeout?

Topic: this bindingDifficulty: Foundation

Passing object.method as a bare function reference detaches it from its receiver.

Solve it with the execution visualizerStep through every binding, function call, and console output below.

Predict the output

Predict the output. Does the callback that setTimeout eventually invokes still know it came from object?

const object = {
  message: 'Hello, World!',
  logMessage() {
    console.log(this.message);
  }
};
setTimeout(object.logMessage, 1000);
Reveal the answer and explanation

Expected output

undefined

Why this happens

object.logMessage is only read as a value here — a reference to the function object — before being handed to setTimeout. The receiver object is not carried along with it.

When the timer fires, setTimeout invokes that function as a plain, receiver-less call. In sloppy mode, default binding takes over and this becomes the global object.

The global object has no message property, so this.message reads undefined.

What this question tests

  • a function value carries no memory of the object it was read from
  • default binding: an unqualified call binds this to the global object in sloppy mode
  • passing a method as a callback is a common way to accidentally lose this

Runtime assumptions

Assumes a classic (non-module, sloppy-mode) browser script, where default binding resolves to window. Strict-mode code would instead leave this as undefined.

Specification references

JavaScript Code EditorDirectly edit or paste custom code
Step 0 of 0
StepSpaceRun
Press → (Step) or Space (Run)
Phase 1: Compilation(Hoisting & Memory Setup)
Phase 2: Execution(Line-by-line Evaluation)
Execution Step Breakdown

Press "→" / click "▶" to step line-by-line, or press "Space" / click "▶ Run" for auto-play.