Preserve method context
A callback inside an object method needs to access the method's object context.
JS Puzzles · Const
Arrow functions do not have their own this; they read it from the surrounding context. This makes them useful as callbacks inside methods when the callback must preserve the method's object context.
An arrow function does not create its own this. When it uses this, JavaScript looks outward to the enclosing lexical environment, so the value comes from the surrounding regular function or method rather than from the way the arrow callback is invoked.
(...args) => expression
(...args) => { body }this binding.this reference inside an arrow resolves through the enclosing scope.forEach can directly reuse the surrounding method's this.title through the inherited context.this is part of a broader limitation: arrows also lack a local arguments binding.new, so it cannot serve as a constructor.this; using it as an object method will not make this refer to that object.bind(this): it closes over the outer this instead of creating a separately bound function.const group = {
title: "Developers",
showList() {
["Ada", "Linus"].forEach(name => {
console.log(`${this.title}: ${name}`);
});
}
};
group.showList();The callback is an arrow function, so it reads this from showList() and preserves the object context.
A callback inside an object method needs to access the method's object context.
A small callback should use surrounding state without manually binding a regular function.
A function should intentionally reject constructor-style invocation.
this differ in an arrow callback and a regular callback?Arrow functions do not have their own this; they obtain it from the surrounding lexical environment. Therefore, a callback arrow inside an object method can use the method's this without losing the object context.
Follow-up: What happens if call() supplies another context? The arrow ignores that attempted context because its this is determined outside the arrow.
A regular function gets this according to how it is called, while an arrow function takes this from outside. This makes arrows useful when a callback should preserve the surrounding method context.
Follow-up: Why not use an arrow for every method? A method often needs its caller-dependent this, which an arrow cannot provide.
this?Arrow functions have no own this, arguments, or constructor behavior. They also cannot be called with new, so they are intended for functions and callbacks rather than constructor roles.
Follow-up: What other function feature is absent? Arrow functions also do not provide their own arguments variable; they use the enclosing scope's one.
Object methods, "this"Arrow functionsforEachbind