Sub topic 8
How this Works in Regular and Arrow Functions
This chapter assumes you know how to write function declarations, function expressions, and arrow functions, and that you have used callbacks such as setTimeout. It explains how JavaScript decides what this refers to, because regular functions and arrow functions decide it in different ways.
The Core Rule
A regular function gets its this from how it is called. The same function can have a different this each time it runs.
An arrow function has no this of its own. It uses the this of the code that surrounds it, as it was when the arrow was created. This is called lexical this.
Regular Functions: The Call Site Decides
For a regular function, check how the call is written:
| Call form | Value of `this` |
|---|---|
| `obj.fn()` | `obj` |
| `fn()` in strict mode | `undefined` |
| `fn()` in sloppy mode | the global object (`globalThis`) |
| `fn.call(x)` / `fn.apply(x)` | `x` |
| `fn.bind(x)()` | `x`, permanently |
| `new Fn()` | the newly created object |
'use strict';
function whoAmI() {
return this;
}
const obj = { name: 'obj', whoAmI };
const other = { name: 'other' };
console.log(obj.whoAmI() === obj); // true
console.log(whoAmI()); // undefined
console.log(whoAmI.call(other).name); // other
const bound = whoAmI.bind(other);
console.log(bound() === other); // trueThe function whoAmI is the same object in every one of these calls. Only the call site changes, and that alone changes this.
Arrow Functions: The Surrounding Scope Decides
An arrow function looks up this the same way it looks up any outer variable. Calling it differently has no effect, and call, apply, and bind cannot override it.
const arrow = () => this;
const target = {};
console.log(arrow.call(target) === target); // false
console.log(arrow.bind(target)() === target); // falseWhen an arrow sits inside a regular method, it takes on that method's this:
const user = {
name: 'Ada',
greet() {
const inner = () => `Hi, ${this.name}`;
return inner();
}
};
console.log(user.greet()); // Hi, AdaThe Classic Problem: Callbacks Lose this
The difference matters most when you pass a function to code that calls it for you. You do not control how setTimeout calls a regular callback, so you do not control its this.
const counter = {
count: 0,
startRegular() {
setTimeout(function () {
console.log(this === counter); // false
}, 0);
},
startArrow() {
setTimeout(() => {
this.count++;
console.log(this.count); // 1
}, 0);
}
};
counter.startRegular();
counter.startArrow();In startRegular, setTimeout calls the callback as a plain function, so this is not counter. In startArrow, the arrow uses the this of startArrow, and that is counter because the call was written counter.startArrow().
Common Errors
- Using an arrow as an object method. In
{ name: 'x', show: () => this.name }, the arrow takesthisfrom the scope around the object literal, not from the object. An object literal does not create athisscope. - Extracting a method.
const f = obj.method; f();drops theobj.part of the call, sothisis lost. Useobj.method.bind(obj)or wrap the call in an arrow:() => obj.method(). - Expecting
bindto fix an arrow. It has no effect onthis. If you need to setthisfrom outside, use a regular function.
Exercise
In strict mode, what does this code log, and why? const box = { size: 3, getSize: () => this?.size, getSizeRegular() { return this.size; } }; console.log(box.getSize(), box.getSizeRegular());
Show answer
It logs "undefined 3". getSize is an arrow, so it takes this from the scope around the object literal, where this is not box, and this?.size is undefined. getSizeRegular is a regular method called as box.getSizeRegular(), so this is box and it returns 3.
Exercise
Given function show() { return this.label; } and const a = { label: 'A' }, what does show.bind(a).call({ label: 'B' }) return?
Show answer
It returns 'A'. bind creates a function whose this is fixed to a. Calling call on the bound function cannot override it.