JavaScriptFundamental (ES6), part 1
Getters and setters in a JavaScript class
42 Getters and setters in a class
fairGive a cart a total that is computed rather than stored, a formatted naira string beside it, and a discountPercent setter that refuses a value outside 0 to 100. Then show what happens when you assign to a getter that has no setter.
Stuck? Three hints, smallest first
- 1.
get total() { ... }is read as a property,cart.total, with no call parentheses. - 2. A setter is the place for validation, because there is no other way in.
- 3. These panels run in strict mode, so writing to an accessor with no setter throws instead of failing quietly.
class Cart {
constructor() {
this.items = [];
}
add(name, kobo) {
this.items.push({ name, kobo });
return this; // so calls chain
}
get total() {
return this.items.reduce((sum, item) => sum + item.kobo, 0);
}
get naira() {
return `₦${(this.total / 100).toFixed(2)}`;
}
set discountPercent(pct) {
if (typeof pct !== 'number' || pct < 0 || pct > 100) {
throw new RangeError(`discount ${pct} is not a percentage`);
}
this._discount = pct;
}
get payable() {
return Math.round((this.total * (100 - (this._discount ?? 0))) / 100);
}
}
const attempt = (fn) => { try { fn(); return 'accepted'; } catch (e) { return e.constructor.name; } };
const cart = new Cart().add('gari', 250000).add('palm oil', 480000);
const beforeDiscount = cart.total;
const formatted = cart.naira;
const storedKeys = Object.keys(cart);
const onPrototype = Object.prototype.hasOwnProperty.call(Cart.prototype, 'total');
const descriptor = Object.getOwnPropertyDescriptor(Cart.prototype, 'total');
const refused = attempt(() => { cart.discountPercent = 120; });
cart.discountPercent = 10;
const payable = cart.payable;
const writeToGetter = attempt(() => { cart.total = 0; });
const serialised = JSON.parse(JSON.stringify(cart));
console.log('total :', beforeDiscount, 'kobo | shown as', formatted);
console.log('stored :', storedKeys, '| total on prototype?', onPrototype);
console.log('120% :', refused, '| 10% payable:', payable);
console.log('cart.total = 0 ->', writeToGetter);
console.log('serialised:', serialised);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the getter computes from the items instead of storing a total', beforeDiscount, 730000);
test('a second getter can format the same data', formatted, '₦7300.00');
test('nothing called total is stored on the instance', storedKeys, ['items']);
test('the accessor lives on the prototype, like a method', onPrototype, true);
test('and it is a get with no set', [typeof descriptor.get, descriptor.set === undefined], ['function', true]);
test('the setter validates, so 120 percent is refused', refused, 'RangeError');
test('a valid discount comes off the computed total', payable, 657000);
test('assigning to a getter-only property throws in strict mode', writeToGetter, 'TypeError');
test('getters do not serialise; only what is stored does', Object.keys(serialised), ['items', '_discount']);
A getter turns a derived value into a property, so callers cannot desynchronise it: there is no total to forget to update when an item is added. The setter is the only door into _discount, which is what makes validating there worthwhile.
Two traps. First, the accessor is on the prototype, so JSON.stringify ignores it — send a cart over the wire and the total vanishes, because JSON carries own enumerable data only. Second, a getter with no setter is not merely ignored on write: in strict mode, and every class body and every panel here is strict, cart.total = 0 throws a TypeError. Outside strict mode the same line fails in silence, which is how this bug survives for months.