Skip to content

OutputNot attempted

Methods passed to setTimeout

const user = {
name: 'Ann',
greet() {
console.log(this === user);
},
greetLater() {
setTimeout(function () {
console.log(this === user);
});
},
greetLaterArrow() {
setTimeout(() => console.log(this === user));
},
};
user.greet();
setTimeout(user.greet);
user.greetLater();
user.greetLaterArrow();

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Line 1: user.greet() is a method call → this === user → true. Passing user.greet to setTimeout DETACHES it: the timer calls it with no receiver: in browsers this is the global object (window, or self in a worker), in Node a Timeout object; never user → false. A regular function inside greetLater: same → false. The arrow in greetLaterArrow borrows that method's this → true. Fix for detached methods: an arrow wrapper, setTimeout(() => user.greet()), or user.greet.bind(user).