CKTIS / JavaScript
Lexical `this` in arrow functions
An arrow function has no `this` binding of its own. It uses the binding from its enclosing lexical context, regardless of how the arrow is called.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
() => this
(...args) => this.method(...args)
() => { return this; }Arrow lexical this means that an arrow function (=>) does not create its own this binding. A reference to this inside it resolves to the nearest enclosing lexical context that provides that binding. An arrow created inside an ordinary method retains access to this from that particular method call, even after the method returns. Different calls to the method can therefore create arrows with different this values.
For an ordinary method called as obj.method(), this is obj. Storing an existing arrow as a property of obj and calling it the same way does not change its this. call() and apply() still pass arguments, and bind() returns a new function and can preset arguments, but none can change the arrow's this. An arrow is not a constructor: using it with new throws a TypeError.
Use an arrow for a callback that should use the enclosing method's this. Use an ordinary method when this should depend on the object used to call it. Do not assume top-level this is the same everywhere: it is undefined in an ECMAScript module and equals globalThis in a classic browser script.
Examples
{
const original = {
label: "A",
makeReader() {
return (suffix = "") => this.label + suffix;
},
};
const other = { label: "B", makeReader: original.makeReader };
const read = original.makeReader();
other.read = read;
console.log(read());
console.log(other.read());
console.log(read.call(other, "!"));
console.log(other.makeReader()());
}Result
A A A! B
`read()` and `other.read()` print `A` because `read` was created during `original.makeReader()`. `call()` passes `"!"` but does not change `this`, so the result is `A!`. Calling `other.makeReader()` creates a new arrow whose `this` is `other`, so calling that arrow produces `B`.
Related lessons
- JavaScript · Lesson 26 · Advanced · Version: 4