Sub topic 6
How this Works in Inherited Methods
This chapter assumes you know how this is bound in an ordinary method call (obj.method()). It also assumes you know how property lookup walks the prototype chain and how Object.create sets a prototype, both covered in earlier chapters. Here we join those ideas: what happens to this when the method JavaScript finds lives on a prototype and not on the object you called it on?
The rule: lookup and binding are separate steps
A method call such as hare.walk() does two independent things:
- Lookup. JavaScript searches for
walk. It checksharefirst and then follows the[[Prototype]]link one object at a time until it finds the property. - Call. JavaScript calls the function it found and sets
thisto the object before the dot. Here that object ishare.
The object where the method was found has no effect on this. Prototypes share the method code. The receiver, meaning the object that appears in the call expression, supplies the data.
const animal = {
walk() {
return `${this.name} walks`;
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
const hare = Object.create(rabbit);
hare.name = 'Hare';
console.log(rabbit.walk()); // "Rabbit walks"
console.log(hare.walk()); // "Hare walks" (found two levels up, this is still hare)
console.log(animal.walk()); // "undefined walks" (this is animal, which has no name)The walk function exists exactly once, on animal. Each call runs that same function with a different this.
Writes through this land on the receiver
The receiver supplies this, so an inherited method that assigns this.something creates or updates a property on the receiver. The prototype is not changed. This is why one prototype can serve many objects that each keep their own state.
const counterProto = {
increment() {
this.count = (this.count ?? 0) + 1;
return this.count;
}
};
const a = Object.create(counterProto);
const b = Object.create(counterProto);
a.increment();
a.increment();
b.increment();
console.log(a.count, b.count); // 2 1
console.log(Object.hasOwn(a, 'count')); // true
console.log('count' in counterProto); // falseThe first call on a reads this.count. It finds nothing anywhere on the chain, so the value is undefined, and ?? 0 turns that into 0. The assignment then creates count as an own property of a. The next chapter looks at what happens when such a write hits a name that already exists on the prototype.
Getters and setters inherit the same way
Accessor properties follow the same rule. A getter defined on a prototype runs with this set to the object you read the property from.
const shape = {
get area() {
return this.width * this.height;
},
set size(n) {
this.width = n;
this.height = n;
}
};
const rect = Object.create(shape);
rect.width = 3;
rect.height = 4;
console.log(rect.area); // 12
const square = Object.create(shape);
square.size = 5; // setter runs with this = square
console.log(square.area); // 25
console.log(Object.hasOwn(square, 'size')); // false (no own "size" was created)
console.log(Object.keys(square)); // ['width', 'height']Common error: losing the receiver
The binding depends on the call expression, so if you take a method off its object you also lose the receiver. This happens when you store a method in a variable, pass it as a callback, or destructure it.
'use strict';
const animal = {
walk() {
return `${this.name} walks`;
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
const walk = rabbit.walk; // copies the function, not the receiver
try {
walk(); // this is undefined in strict mode
} catch (err) {
console.log(err instanceof TypeError); // true
}
const bound = rabbit.walk.bind(rabbit);
console.log(bound()); // "Rabbit walks"
console.log(animal.walk.call(rabbit)); // "Rabbit walks" (explicit receiver)
setTimeout(() => console.log(rabbit.walk()), 0); // "Rabbit walks"In sloppy mode, this in the extracted call is globalThis and not undefined. The code then fails silently with output like "undefined walks" instead of throwing. Class bodies and ES modules always run in strict mode, so there you get the TypeError.
The line animal.walk.call(rabbit) matters for later chapters. It calls a prototype's method directly while keeping the current object as this. Constructor inheritance relies on this pattern when a child method calls the parent's version.
Common error: arrow functions on prototypes
Arrow functions have no this of their own. They capture this from the surrounding scope at the point where they are created. If you put an arrow function on a prototype, the receiver is ignored completely.
function makeProto() {
return {
regular() {
return this.label;
},
arrow: () => this.label // captures makeProto's this, permanently
};
}
const proto = makeProto.call({ label: 'outer' });
const obj = Object.create(proto);
obj.label = 'obj';
console.log(obj.regular()); // "obj"
console.log(obj.arrow()); // "outer"
console.log(obj.arrow.call({ label: 'other' })); // "outer" (call cannot rebind it)Methods meant to be shared through a prototype should use method syntax or function. Use arrow functions for callbacks inside those methods, where capturing the method's this is the behavior you want.
Summary of call forms
| Call form | Value of `this` inside an inherited method |
|---|---|
| `obj.method()` | `obj`, wherever on the chain `method` was found |
| `proto.method()` | `proto` itself |
| `const f = obj.method; f()` | `undefined` (strict) or `globalThis` (sloppy) |
| `proto.method.call(obj)` | `obj` |
| `obj.method.bind(obj)()` | `obj`, fixed permanently |
| Arrow function stored on a prototype | The `this` of the scope where the arrow was created |
Exercise
Given const base = { greet() { return 'Hi ' + this.name; }, name: 'Base' }; const child = Object.create(base); child.name = 'Child'; const grand = Object.create(child);, what do grand.greet() and base.greet.call(child) return, and why?
Show answer
Both return "Hi Child". For grand.greet(), this is grand. grand has no own name, so reading this.name walks the chain and finds "Child" on child before it reaches "Base". For base.greet.call(child), call sets this to child explicitly, and child has its own name of "Child".
Exercise
A prototype defines reset() { this.items = []; }. Two objects created from it each call reset() and then push values into this.items. Do they share one array? What changes if the prototype instead has items: [] and reset is never called?
Show answer
After reset() they do not share an array. Each call assigns a new array to the receiver as an own property. Without reset, both objects read items through the chain and get the same array on the prototype, so a push through either object is visible to both.
Exercise
Why does button.addEventListener('click', counter.increment) fail to update counter.count, and give two ways to fix it.
Show answer
Passing counter.increment passes only the function, so the receiver is lost. When the event fires, this is the element (or undefined in other callback contexts), not counter. Fix it with counter.increment.bind(counter) or with a wrapper arrow function () => counter.increment(), which calls the method with counter as the receiver.