Sub topic 10
Arrow Functions and Lexical this
Earlier chapters showed that a regular function gets its this from the call site. The same function can see a different this each time, depending on whether it was called as a method, through call, with new, or as a plain function. Arrow functions work differently. They never get a this of their own. This chapter covers how that works, why it fixes the "lost this" problem in callbacks, and when it causes bugs of its own.
This chapter assumes you know the binding rules from earlier chapters: default, implicit, explicit with call/apply/bind, and new. It also assumes you know how closures capture variables from an enclosing scope.
The Core Rule: No Own this
A regular function creates a new this binding every time it runs. An arrow function does not. When code inside an arrow mentions this, JavaScript looks it up the same way it looks up any other free variable. It walks outward through the enclosing scopes until it reaches a scope that has a this binding.
Only two kinds of scope have a this binding:
- A non-arrow function (a function declaration, a function expression, a method, a constructor, or a class body's methods and field initializers).
- The top level of a script or module.
So the this inside an arrow is the this of the nearest enclosing non-arrow function. If there is none, it is the top-level this. People call this lexical this, because the source text decides which scope supplies it. The way the arrow is called has no effect.
The Problem Arrows Solve
Before ES2015, a callback inside a method lost this, because the callback was called as a plain function. The usual fix was to copy this into an ordinary variable that the callback could close over:
'use strict';
const timer = {
seconds: 0,
startOld() {
const self = this; // capture the method's this in a variable
setTimeout(function () {
// A regular function called by setTimeout: its own this is not timer.
self.seconds++;
console.log('old style:', self.seconds);
}, 10);
},
startNew() {
setTimeout(() => {
// No own this: resolves to startNew's this, which is timer.
this.seconds++;
console.log('arrow style:', this.seconds);
}, 20);
}
};
timer.startOld(); // old style: 1
timer.startNew(); // arrow style: 2The arrow version does the same thing as const self = this, but the language does the capturing for you. You can think of an arrow's this as a closure over the enclosing function's this.
Lexical Does Not Mean Fixed Forever
One common misunderstanding is that an arrow's this is chosen once, when the code is written. The source text only decides which scope supplies this. The value comes from that scope's invocation at the moment the arrow is created. If the enclosing function runs again with a different this, the arrows created during that run capture the new value.
'use strict';
function makeReader() {
return () => this;
}
const a = { name: 'a' };
const b = { name: 'b' };
const fromA = makeReader.call(a); // makeReader runs with this = a
const fromB = makeReader.call(b); // makeReader runs with this = b
console.log(fromA().name); // 'a'
console.log(fromB().name); // 'b'
console.log(fromA.call(b).name); // 'a', call cannot change itThe enclosing function's this is still dynamic and still follows every rule from earlier chapters. The arrow only freezes whatever value that particular call produced.
When the enclosing method is extracted
So an arrow helps only if the function around it was called correctly. If the outer method loses its binding, every arrow created inside it inherits the broken value.
'use strict';
const counter = {
count: 0,
makeIncrementer() {
return () => ++this.count;
}
};
const inc = counter.makeIncrementer(); // method call: this = counter
console.log(inc()); // 1
console.log(inc()); // 2
const detached = counter.makeIncrementer;
const broken = detached(); // plain call in strict mode: this = undefined
try {
broken();
} catch (e) {
console.log(e instanceof TypeError); // true: cannot read 'count' of undefined
}The arrow did not cause this bug, and it cannot fix it. When you trace an arrow's this, look at how the nearest enclosing regular function was called.
Nested arrows
Arrows inside arrows keep walking outward, so the whole chain shares one this:
'use strict';
const report = {
title: 'Q3',
rows: [[1, 2], [3, 4]],
render() {
return this.rows.map(row =>
row.map(cell => `${this.title}:${cell}`) // both arrows reach render's this
);
}
};
console.log(report.render()); // [ [ 'Q3:1', 'Q3:2' ], [ 'Q3:3', 'Q3:4' ] ]What You Cannot Do to an Arrow's this
Since an arrow has no this slot, the tools that set this on regular functions have nothing to set.
const arrow = () => this;
// call, apply, and bind accept a thisArg but silently ignore it.
console.log(arrow.call({ x: 1 }) === arrow()); // true
console.log(arrow.apply({ x: 1 }) === arrow()); // true
const bound = arrow.bind({ x: 1 });
console.log(bound() === arrow()); // true
// bind still works for arguments, just not for this.
const add = (p, q) => p + q;
const addTen = add.bind(null, 10);
console.log(addTen(5)); // 15
// Arrows are not constructors.
console.log(arrow.prototype); // undefined
try {
new arrow();
} catch (e) {
console.log(e instanceof TypeError); // true: arrow is not a constructor
}Every row of the precedence table from the previous chapter assumes a regular function. For arrows, the order is short: lexical this applies and nothing else can override it. new does not take priority because it throws instead.
Arrows also lack other bindings that come with a regular function's invocation. They have no own arguments, super, or new.target, and they resolve all three lexically the same way they resolve this. Use rest parameters ((...args) => {}) where you would have reached for arguments.
When Arrows Are the Wrong Choice
Lexical this is what you want for callbacks that need the outer this. It is the wrong behavior whenever a function is supposed to receive this from its call site.
Methods in object literals
The braces of an object literal do not create a scope. An arrow written as a property value takes this from whatever code surrounds the whole literal. That is usually the top level, and it is never the object.
'use strict';
const account = {
balance: 100,
isSelfArrow: () => this === account,
isSelfMethod() {
return this === account;
}
};
console.log(account.isSelfArrow()); // false: this is the top-level this
console.log(account.isSelfMethod()); // true: implicit binding through the dotWhat a top-level this contains depends on the file type: globalThis in a classic script, undefined in an ES module, module.exports in a CommonJS file. In none of these cases is it account. Code like getBalance: () => this.balance therefore either throws or returns undefined, depending on where it runs.
Prototype methods
The same applies to methods assigned to a prototype:
'use strict';
function Person(name) {
this.name = name;
}
Person.prototype.greetArrow = () => `Hi, ${this && this.name}`;
Person.prototype.greetRegular = function () {
return `Hi, ${this.name}`;
};
const p = new Person('Lin');
console.log(p.greetRegular()); // 'Hi, Lin'
console.log(p.greetArrow()); // 'Hi, undefined' (or similar): never pA shared method needs a dynamic this so it can serve every instance. An arrow defined once at the top level can only ever see the top-level this.
APIs that pass you a meaningful this
Some APIs call your function with a specific this on purpose. Examples are a thisArg passed to array methods, libraries that call hooks with a context object, and DOM listeners that receive the element. An arrow throws away that value. The chapter on callbacks and event handlers covers those conventions. The general rule is this: if documentation says "this will be …", give it a regular function.
Functions you plan to call with new
Arrows cannot be constructors. A factory that should support new has to be a regular function or a class.
Choosing Between an Arrow and a Regular Function
| Situation | Use | Reason |
|---|---|---|
| Callback inside a method that needs the method's `this` | Arrow | Captures the outer `this` without `self` or `bind` |
| Method on an object literal or prototype | Regular method syntax | Needs implicit binding from the call site |
| Function that will be called with `new` | Regular function or class | Arrows have no `prototype` and throw under `new` |
| API supplies `this` (thisArg, hook context, DOM listener using `this`) | Regular function | An arrow would ignore the supplied value |
| Small pure helper that never touches `this` | Either | `this` does not matter; arrows are just shorter |
| Need `arguments` or `super` of the function itself | Regular function | Arrows resolve these lexically |
Cost and readability
Each evaluation of an arrow expression creates a new function object, the same as a function expression does. An arrow inside a method that runs often creates a fresh closure on each call. That rarely matters, but it does mean two arrows created by separate calls are never ===. This becomes relevant when you need the same reference later, for example to call removeEventListener. Store the arrow in a variable or property if you will need to refer to it again.
A useful habit when reading code: for any this inside an arrow, put your finger on the nearest enclosing function, method, or class member. The question "what is this here?" becomes "how was that function called?" From there, the binding rules from earlier chapters answer it.
The next chapter applies this in classes, where arrow class fields give each instance its own pre-bound handler.
Exercise
In an ES module, what does each of the three console.log lines print, and why? const box = { value: 42, outer() { const viaArrow = () => this.value; const viaRegular = function () { return this && this.value; }; return [viaArrow(), viaRegular(), viaArrow.call({ value: 7 })]; } }; console.log(box.outer()); const f = box.outer; try { console.log(f()); } catch (e) { console.log(e.constructor.name); } console.log(box.outer.call({ value: 1 }));
Show answer
The first line prints [42, undefined, 42]. outer is called as a method, so its this is box. The arrow reads box.value both times, because call cannot override an arrow's this. viaRegular is called as a plain function in strict module code, so its this is undefined and the guard returns undefined. The second line prints TypeError. f() is a plain call, so outer's this is undefined, and viaArrow() then tries to read undefined.value. The third line prints [1, undefined, 1], because the arrows inherit outer's this, which call set to { value: 1 }.
Exercise
A colleague writes const settings = { theme: 'dark', describe: () => Theme: ${this.theme} }; and finds that settings.describe() never prints 'dark'. They try settings.describe.call(settings), and it still fails. Explain both failures and give a fix.
Show answer
describe is an arrow, so it has no own this. It resolves this lexically, and the object literal's braces do not create a scope, so this comes from the surrounding top level: undefined in a module (which throws) or globalThis/module.exports elsewhere (which gives undefined). call cannot help, because arrows silently ignore a thisArg. The fix is to use method syntax, describe() { return Theme: ${this.theme}; }, so that settings.describe() gets settings through implicit binding.
Exercise
Rewrite this method so the callback works without self, bind, or a thisArg, and say which binding rule supplies the final value of this: tally: { total: 0, addAll(nums) { const self = this; nums.forEach(function (n) { self.total += n; }); return self.total; } }
Show answer
Write addAll(nums) { nums.forEach(n => { this.total += n; }); return this.total; }. The arrow resolves this to addAll's this. When you call tally.addAll([1, 2]), implicit binding sets that to tally, because tally is the object before the dot.