JAVASCRIPT / CHAPTER 11
Methods, receivers, and class invariants
IntermediateKeep object behavior connected to the intended receiver.
By the end of this chapter
- Trace this in a method call
- Bind callbacks when required
- Enforce state rules inside methods
The idea
A class groups construction and methods, but each instance still has its own state. In an ordinary method call such as counter.add(2), the object before the dot supplies this. Extracting the function and invoking it alone loses that receiver. Class methods execute in strict mode, so an unbound call cannot quietly use a global object as this.
When passing a method as a callback, bind the receiver or pass a wrapper that calls the method on its object. Put invariants inside the method rather than relying on every caller to enforce them. A counter that accepts only nonnegative integers should reject invalid changes before touching its state. Do not confuse const on the instance variable with immutability of its fields.
class Counter {
constructor() { this.value = 0; }
add(n) {
if (!Number.isInteger(n) || n < 0) throw new RangeError("n");
this.value += n;
}
}
const c = new Counter();
const add = c.add.bind(c);
add(3);
console.log(c.value);3
bind creates a function that retains c as its receiver. Validation precedes mutation.
Try it yourself
Implement a limited counter whose rejected increments leave its previous value intact.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING