Sub topic 8
How this Works in Regular and Arrow Functions
This chapter assumes you know how to declare regular and arrow functions, how to call methods on objects, and the difference between strict mode and sloppy (non-strict) mode at a basic level. Callbacks, class fields, and constructors each get their own chapters later. Here the focus is the rule that decides what this is.
A regular function has no fixed this. JavaScript works out a new this every time the function is called, based on how it is called (the call site), not where it was written. An arrow function never gets a this of its own. It uses the this of the scope it was defined in, the same way it would use any outer variable.
The Call Site Decides for Regular Functions
The same function can see different values of this depending on what sits to the left of the dot when you call it.
'use strict';
function whoAmI() {
return this === undefined ? 'undefined' : this.name;
}
const ada = { name: 'Ada', whoAmI };
const grace = { name: 'Grace', whoAmI };
console.log(ada.whoAmI()); // Ada
console.log(grace.whoAmI()); // Grace
const loose = ada.whoAmI;
console.log(loose()); // undefinedThere is only one function object here. ada.whoAmI and grace.whoAmI point to it, and so does loose. The function never belonged to ada. During the call ada.whoAmI(), JavaScript sets this to the object the function was read from. loose() has no object in front of it, so no object gets passed as this.
A regular function call follows four rules. They are listed here from highest priority to lowest:
| Rule | Call shape | Value of `this` |
|---|---|---|
| `new` binding | `new fn()` | The newly created object |
| Explicit binding | `fn.call(obj)`, `fn.apply(obj)`, `fn.bind(obj)()` | `obj` |
| Implicit binding | `obj.fn()` or `obj['fn']()` | `obj` |
| Default binding | `fn()` | `undefined` in strict mode, `globalThis` in sloppy mode |
The new rule comes up in the chapter on constructors. The other three rules come up in everyday code.
Default Binding and Strict Mode
When nothing in the call supplies a this, the outcome depends on the mode of the called function's code.
function sloppy() {
return this === globalThis;
}
function strict() {
'use strict';
return this;
}
console.log(sloppy()); // true (when run as a classic script or CommonJS file)
console.log(strict()); // undefinedStrict mode also changes what happens to primitive and empty values passed as this:
| Passed as `this` | Strict mode receives | Sloppy mode receives |
|---|---|---|
| `undefined` or `null` | `undefined` or `null` | `globalThis` |
| `5` | `5` (a number) | A `Number` wrapper object |
| `'hi'` | `'hi'` (a string) | A `String` wrapper object |
| An object | That object | That object |
Explicit Binding with call, apply, and bind
Every regular function has three methods that let you choose this yourself.
call(thisArg, ...args)calls the function right away, passing the arguments one by one.apply(thisArg, argsArray)calls it right away, passing the arguments as an array.bind(thisArg, ...args)calls nothing. It returns a new bound function withthisfixed, and optionally some leading arguments fixed too.
'use strict';
function describe(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
const ada = { name: 'Ada' };
const grace = { name: 'Grace' };
console.log(describe.call(ada, 'Hi', '!')); // Hi, I am Ada!
console.log(describe.apply(ada, ['Hello', '.'])); // Hello, I am Ada.
const bound = describe.bind(ada, 'Hey');
console.log(bound('?')); // Hey, I am Ada?
grace.bound = bound;
console.log(grace.bound('!')); // Hey, I am Ada!
console.log(bound.call(grace, '!')); // Hey, I am Ada!
console.log(bound.bind(grace)('!')); // Hey, I am Ada!The last three lines show the key behavior of bind. A bound function keeps its this for good. Implicit binding (grace.bound()), call, and a second bind all fail to change it. The second bind can still add more preset arguments, but it cannot replace this. The only rule that can override a bound this is new.
Arrow Functions Use Lexical this
An arrow function skips all four rules. When code inside an arrow reads this, JavaScript looks it up in the surrounding scope, the same way it would look up a variable the arrow doesn't declare. This is called lexical this: the value depends on where the arrow sits in the source code.
'use strict';
const ada = { name: 'Ada' };
function outer() {
return () => this.name;
}
const arrow = outer.call(ada);
console.log(arrow()); // Ada
console.log(arrow.call({ name: 'Grace' })); // Ada
console.log(arrow.bind({ name: 'Grace' })()); // AdaThe arrow was created during the call outer.call(ada), where this was ada. That value stays with the arrow for as long as the arrow exists. Calling call or bind on an arrow works without error, but the thisArg is silently ignored. Only the extra arguments are passed through.
The Nested Function Problem
Before arrow functions existed, the most common this bug was a helper function nested inside a method:
'use strict';
const cart = {
items: [10, 20],
taxRate: 0.1,
totalWithRegular() {
function addTax(price) {
return price * (1 + this.taxRate); // this is undefined here
}
try {
return this.items.map(addTax);
} catch (e) {
return e.constructor.name;
}
},
totalWithSelf() {
const self = this;
function addTax(price) {
return price * (1 + self.taxRate);
}
return this.items.map(addTax);
},
totalWithArrow() {
const addTax = (price) => price * (1 + this.taxRate);
return this.items.map(addTax);
}
};
console.log(cart.totalWithRegular()); // TypeError
console.log(cart.totalWithSelf()); // [ 11, 22 ]
console.log(cart.totalWithArrow()); // [ 11, 22 ]Inside totalWithRegular, this is cart. The inner addTax is a separate regular function, though, and map calls it with no object in front, so default binding gives it undefined. The old fix was to copy this into an ordinary variable such as self or that, which the inner function captures through its closure. An arrow does exactly that without the extra variable.
Where Arrows Get It Wrong
Lexical this helps inside a method. It causes bugs when the arrow is the method:
'use strict';
const outerThis = this;
const profile = {
name: 'Ada',
regular() {
return this === profile;
},
arrow: () => this === profile
};
console.log(profile.regular()); // true
console.log(profile.arrow()); // false
console.log(profile.arrow.call(profile)); // falseAn object literal does not create a scope. The arrow assigned to arrow therefore takes this from the code around the literal, which is the module or script top level. outerThis there is module.exports in CommonJS, undefined in an ES module, or globalThis in a classic script. In none of these cases is it profile. Writing profile.arrow() does not help, because arrows ignore implicit binding.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Pulling a method into a variable: `const f = obj.method; f()` | Default binding: `undefined` in strict mode | Call it as `obj.method()`, or use `obj.method.bind(obj)` |
| Using an arrow as an object method | `this` is the outer scope, not the object | Use method shorthand: `method() { ... }` |
| Expecting `call`/`bind` to change an arrow's `this` | The `thisArg` is silently ignored | Use a regular function if callers need to supply `this` |
| Binding twice to switch objects | The first `bind` wins | Keep a reference to the original unbound function |
| Testing in sloppy mode, shipping in a module | Code that "worked" on `globalThis` now throws | Add `'use strict'` or test as an ES module |
Summary
- A regular function gets
thisat call time. In priority order, it comes fromnew, explicit binding, implicit binding, or the default. - Default binding gives
undefinedin strict mode andglobalThisin sloppy mode. bindfixesthispermanently. Onlynewcan override it.- An arrow function has no
thisof its own. It readsthisfrom the nearest enclosing non-arrow scope, andcall,apply,bind, andobj.prefixes cannot change it.
Exercise
In strict mode, given function show() { return this?.id; }, const a = { id: 1, show };, and const b = { id: 2 };, what do a.show(), show.call(b), (0, a.show)(), and show.bind(a).call(b) return?
Show answer
1, 2, undefined, and 1. a.show() uses implicit binding. show.call(b) uses explicit binding. (0, a.show)() evaluates the comma expression to the bare function value, so the call has no object in front and gets default binding (undefined in strict mode). The bound function keeps a even when called with call(b).
Exercise
Why does const timer = { seconds: 0, tick: () => { this.seconds++; } }; timer.tick(); fail to update timer.seconds, and how do you fix it?
Show answer
tick is an arrow, so its this comes from the scope around the object literal (the module or script top level), not from timer. The timer. prefix is ignored. In an ES module this is undefined, so the call throws. In CommonJS, this is module.exports, and the result is NaN stored on that object. Fix it with method shorthand: tick() { this.seconds++; }.
Exercise
Inside a method run() { const f = () => this; return f.call(null); } called as obj.run(), what is returned, and what would change if f were a regular function in strict mode?
Show answer
It returns obj, because the arrow takes this from run, where this is obj, and the null passed to call is ignored. If f were a regular strict-mode function, call(null) would set this to null, so null would be returned.