Interview questions
Output question: this in methods vs arrows
An output-based question probing this binding.
This tests whether you understand how this is resolved for regular methods versus arrow functions.
Regular functions get their `this` at call time; arrows freeze it at definition time.
Key concepts
1
A regular method called as obj.method() binds this to obj. But a regular function passed as a callback (like setTimeout) loses that binding and this becomes undefined (strict) or the global object. An arrow function captures this lexically, so it keeps the surrounding this.
obj.method()thisobjsetTimeoutundefined
2
Answer: the regular-function timeout logs undefined; the arrow-function timeout logs Ada.
Answer:undefinedAda
javascript
const user = {
name: 'Ada',
regularLater() { setTimeout(function () { console.log(this.name); }, 0); },
arrowLater() { setTimeout(() => console.log(this.name), 0); },
};
user.regularLater(); // undefined
user.arrowLater(); // 'Ada'