Question 18 / 31
Why does the arrow-function property fail to read the object?
Topic: this bindingDifficulty: Intermediate
Unlike a shorthand method, an arrow function never binds its own this to the object that holds it.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
Predict both lines. greet and farewell are both properties of the same object — why do they resolve this differently?
const object = {
who: 'World',
greet() {
return `Hello, ${this.who}!`;
},
farewell: () => {
return `Goodbye, ${this.who}!`;
}
};
console.log(object.greet());
console.log(object.farewell());Reveal the answer and explanation
Expected output
Hello, World!
Goodbye, undefined!Why this happens
greet is defined with shorthand method syntax, an ordinary function. Calling object.greet() is a member-expression call, so implicit binding sets this to object and this.who reads "World".
farewell is an arrow function. Arrow functions have no [[ThisMode]] of their own — at creation time they capture whatever this was in the surrounding lexical scope, permanently, regardless of how they are later called.
The arrow was created at the top level of the script, where this is the global object, not object. The global object has no who property, so this.who reads undefined and farewell logs "Goodbye, undefined!" even though it was called as object.farewell().
What this question tests
- ordinary methods use implicit binding; arrow functions never do
- an arrow function closes over this lexically, at the point it is created
- object.farewell() looks like a method call, but the receiver is ignored
Runtime assumptions
Assumes a classic (non-module) script, where top-level this is the global object. In an ES module, top-level this is undefined instead, and this.who would throw.