Sub topic 11
Methods, Callbacks, and Class Field Arrows
This chapter assumes you already know how this is set in regular functions, where it depends on the call site, and in arrow functions, where it is taken from the surrounding scope. Here you will use those rules to choose a function form in three places where it matters: object methods, callbacks, and class fields.
Object Methods: Use Method Shorthand
An object method should almost always be a regular function, written with method shorthand. When you call obj.method(), the call sets this to obj. An arrow function ignores the call site and keeps the this of the code around the object literal. That outer this is never the object.
const user = {
name: 'Ada',
regular() {
return this === user;
},
arrow: () => this === user
};
console.log(user.regular()); // true
console.log(user.arrow()); // falseA common mistake is to write arrow: () => this.name and then get undefined, or a crash, in production. Object literals do not create a this scope. Only functions do.
Callbacks: Detached Methods Lose `this`
If you pass a method by reference, such as cart.add, you pass only the function. The object is not passed with it. The function that receives it calls it as a plain function, so in strict code, which includes every class body, this is undefined.
class Cart {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
}
const cart = new Cart();
try {
['a'].forEach(cart.add);
} catch (e) {
console.log(e instanceof TypeError); // true
}
['a', 'b'].forEach(item => cart.add(item)); // arrow wrapper
['c'].forEach(cart.add.bind(cart)); // bound copy
['d'].forEach(cart.add, cart); // forEach's thisArg
console.log(cart.items); // [ 'a', 'b', 'c', 'd' ]Arrow functions are the natural choice for inline callbacks. They keep the surrounding this, so inside a method you can write this.items.map(x => this.format(x)) and both uses of this refer to the same object.
Class Field Arrows: Bound Handlers With Costs
A class field initialized with an arrow function runs once per instance, inside the constructor. Its this is therefore fixed to that instance, so you can detach it safely. This is why React-style components and event handlers often use the pattern. It has costs, though.
class Button {
label = 'OK';
handleArrow = () => this.label;
handleMethod() {
return this.label;
}
}
const a = new Button();
const b = new Button();
console.log(a.handleArrow === b.handleArrow); // false: one copy per instance
console.log(a.handleMethod === b.handleMethod); // true: shared on the prototype
console.log('handleArrow' in Button.prototype); // false
class Base {
greet = () => 'base';
}
class Child extends Base {
greet() {
return 'child';
}
}
console.log(new Child().greet()); // baseThe last result surprises many people. The field greet is an own property of the instance, so it shadows the greet method that Child defines on its prototype. Field arrows also cannot be reached through super.greet(), and test spies placed on the prototype will not see them.
| Form | `this` | Location | Safe to detach | Overridable |
|---|---|---|---|---|
| Method `m() {}` | Call site | Prototype (shared) | No | Yes |
| Field `m = () => {}` | Instance, fixed | Each instance | Yes | Not by subclass methods |
| Method plus `bind` in constructor | Instance, fixed | Each instance (bound copy) | Yes | Partly: the bound copy calls the subclass method |
Exercise
A Timer class has start() { setInterval(this.tick, 1000); } and tick() { this.seconds++; }. Why does it fail, and what are two fixes?
Show answer
this.tick is passed without its object, so setInterval calls it with this not set to the instance. It is undefined in a class's strict code (in browsers, setInterval may set it to the global object instead), so this.seconds++ either throws or updates the wrong object. Fix 1: setInterval(() => this.tick(), 1000). Fix 2: make tick an arrow class field, tick = () => { this.seconds++; }, or bind it in the constructor with this.tick = this.tick.bind(this).
Exercise
Why does new Child().greet() return 'base' when Child defines its own greet() method and Base defines greet as an arrow class field?
Show answer
Base's field initializer creates greet as an own property on each instance. Own properties are found before prototype properties, so the instance's arrow hides Child.prototype.greet.