Sub topic 7
Computed Properties with Getters and Setters
This chapter assumes you can write a class with a constructor, instance methods, and public fields, and that you know how methods end up on the prototype.
What accessors do
A getter is a method that runs when code reads a property. A setter is a method that runs when code assigns to that property. Callers use ordinary property syntax, with no parentheses, while the class runs code behind the scenes. Use accessors when a value is derived from other state or when assignments need checking.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature(100);
console.log(t.fahrenheit); // 212
t.fahrenheit = 32;
console.log(t.celsius); // 0The class stores only celsius. The fahrenheit value is computed each time it is read, so the two can never get out of sync.
Validating assignments
A setter can reject bad input. Keep the real value in a separate backing property. By convention its name starts with an underscore. The chapter on private fields shows a way to hide it completely.
class Account {
_balance = 0;
get balance() {
return this._balance;
}
set balance(value) {
if (typeof value !== 'number' || value < 0) {
throw new RangeError(`Invalid balance: ${value}`);
}
this._balance = value;
}
}
const acct = new Account();
acct.balance = 50;
console.log(acct.balance); // 50
try {
acct.balance = -10;
} catch (err) {
console.log(err.message); // 'Invalid balance: -10'
}Where accessors live
Like methods, accessors are defined once on the prototype, not on each instance:
class Temperature {
constructor(celsius) { this.celsius = celsius; }
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
}
const desc = Object.getOwnPropertyDescriptor(Temperature.prototype, 'fahrenheit');
console.log(typeof desc.get, desc.set); // 'function' undefined
console.log(Object.hasOwn(new Temperature(0), 'fahrenheit')); // falseBecause accessors sit on the prototype, JSON.stringify and Object.keys skip them. Those functions only look at an instance's own properties.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Setter assigns to its own name (`set x(v) { this.x = v; }`) | The setter calls itself until a `RangeError: Maximum call stack size exceeded` | Store the value in a different property, such as `_x` |
| Calling a getter like a method: `t.fahrenheit()` | `TypeError`, because the returned number is not a function | Read it without parentheses |
| Assigning to a getter-only property | `TypeError` in strict code and modules. In sloppy scripts the assignment is silently ignored | Add a setter, or treat the property as read-only on purpose |
| Slow work inside a getter | The cost is paid on every read, and the property syntax hides it | Cache the result, or use a method so the cost is visible |
Exercise
Write a Rectangle class with width and height set in the constructor, a getter area, and a setter area that keeps the current width and recalculates height so the new area holds. What does new Rectangle(2, 3) report for area after you assign r.area = 10, and what is r.height?
Show answer
class Rectangle { constructor(w, h) { this.width = w; this.height = h; } get area() { return this.width * this.height; } set area(v) { this.height = v / this.width; } } — After r.area = 10, r.area is 10 and r.height is 5.
Exercise
Why does set name(v) { this.name = v; } crash, and how do you fix it?
Show answer
Inside the setter, this.name = v calls the same setter again, so it recurses until the stack overflows. Store the value under a different key, such as this._name = v, and have the getter return this._name.