How does this behave inside an arrow function?
An arrow function has no this of its own. It uses the this of the surrounding code where it was written, and call, apply and bind cannot change it.
Explain it simply
A regular function is like a taxi: its meaning of "here" depends on who called it. An arrow function is like a passenger who always carries the location of the place they boarded from.
Because it takes this from the enclosing scope, an arrow function is the right choice for callbacks inside methods, where you want this to stay the object. It is the wrong choice for an object method or a constructor, where you want this to be set by the call.
Arrow functions also cannot be used with new, and .call(other) on them ignores other.
Example
const counter = {
count: 0,
startArrow() {
[1, 2, 3].forEach(() => {
this.count++; // this is counter, taken from startArrow
});
return this.count;
}
};
console.log(counter.startArrow()); // Output: 3
const arrow = () => 5;
const bound = arrow.bind({ x: 1 });
console.log(bound()); // Output: 5Had the callback been a regular function () { this.count++ }, its this would not be counter, and the count would not increase.
What to say in the interview
"Arrow functions do not create their own this; they capture it lexically from the enclosing scope. That makes them ideal for callbacks inside methods, but I avoid them as object methods or constructors because their this cannot be re-bound with call, apply or bind."
Common mistakes
- Writing an object method as an arrow function and expecting this to be the object.
- Trying to fix an arrow's this with bind. It has no effect.