Sub topic 5
How this Works in Inherited Methods
This chapter assumes you know how this is bound in an ordinary method call (obj.method()), and that you have read the earlier chapters on the prototype chain and Object.create.
The rule: lookup and `this` are separate
A call like rabbit.walk() does two separate things:
- Lookup. JavaScript searches for
walkonrabbit. Ifrabbitdoesn't have it, the search moves along the prototype chain until the property is found. - Binding. JavaScript calls the function it found, and
thisis set to the object before the dot. In this call, that object israbbit.
Where the method is stored has no effect on this. A method that lives on a prototype still runs with this set to the object you called it on, which is why one method on a prototype can serve many objects.
Reads and writes through `this`
const animal = {
sleep() {
this.isSleeping = true;
},
describe() {
return `${this.name} is ${this.isSleeping ? 'asleep' : 'awake'}`;
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
const fox = Object.create(animal);
fox.name = 'Fox';
rabbit.sleep();
console.log(rabbit.describe()); // "Rabbit is asleep"
console.log(fox.describe()); // "Fox is awake"
console.log(Object.hasOwn(rabbit, 'isSleeping')); // true
console.log(animal.isSleeping); // undefinedsleep is defined on animal, but this.isSleeping = true creates the property on rabbit. Methods inherited from a prototype read and write the receiver's state. The prototype holds the shared behavior, and each object holds its own data. fox is unaffected.
Losing the receiver
this is set by how a function is called, not by where it is stored. If you take an inherited method off its object, the receiver is gone:
'use strict';
const animal = {
describe() {
return `${this.name} is here`;
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
const detached = rabbit.describe;
try {
detached(); // this is undefined in strict mode
} catch (e) {
console.log(e instanceof TypeError); // true
}
const bound = rabbit.describe.bind(rabbit);
console.log(bound()); // "Rabbit is here"
console.log(animal.describe.call(rabbit)); // "Rabbit is here"Passing rabbit.describe as a callback, for example to setTimeout or an event listener, causes the same problem. To fix it, use bind or wrap the call in a function: () => rabbit.describe().
call also lets you run a prototype's method directly on any object. Later chapters use this pattern for calling a parent's method.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Property appears on the instance, not the prototype | A write through `this` targets the receiver | This is the intended behavior. Write to the prototype explicitly if you really need shared state |
| `TypeError: Cannot read properties of undefined` | The method was detached from its object | Use `bind`, `call`, or a wrapper function |
| `this` is the wrong object | An arrow function was used as a prototype method | Use method shorthand |
Exercise
Given const base = { inc() { this.n = (this.n || 0) + 1; } }; const a = Object.create(base); a.inc(); a.inc();, what are a.n, base.n, and Object.hasOwn(a, 'n')?
Show answer
a.n is 2, base.n is undefined, and Object.hasOwn(a, 'n') is true. Both calls run with this set to a, so the writes create and then update an own property on a. base is never modified.
Exercise
Why does setTimeout(rabbit.describe, 0) fail to print "Rabbit is here", and what is one fix?
Show answer
setTimeout receives only the function and later calls it without a receiver, so this is not rabbit. One fix is setTimeout(() => rabbit.describe(), 0). Another is setTimeout(rabbit.describe.bind(rabbit), 0).