Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Enumerable getters three ways in JavaScript

72 The same getter, three enumerabilities

hard

Define the same computed total three ways: in an object literal, with Object.defineProperty, and as a class getter. Read all three descriptors, then check which of them Object.keys, JSON.stringify and spread can see. Then find out what spread does to a getter.

Stuck? Three hints, smallest first
  1. 1. A getter in a literal is enumerable and configurable. The same getter through defineProperty defaults to neither.
  2. 2. A class getter lives on the prototype, and nothing on a prototype is an own property of the instance.
  3. 3. Spread copies values. Ask what it does with an accessor.

The answer

const literal = {
  fare: 400,
  get total() { return this.fare + 50; },
};

const defined = { fare: 400 };
Object.defineProperty(defined, 'total', { get() { return this.fare + 50; } });

class Trip {
  constructor(fare) { this.fare = fare; }
  get total() { return this.fare + 50; }
}
const instance = new Trip(400);

const shape = (obj, key) => {
  const d = Object.getOwnPropertyDescriptor(obj, key);
  return d ? [typeof d.get, d.enumerable, d.configurable] : 'no own property';
};

const literalShape = shape(literal, 'total');
const definedShape = shape(defined, 'total');
const instanceShape = shape(instance, 'total');
const prototypeShape = shape(Trip.prototype, 'total');

const allThreeRead = [literal.total, defined.total, instance.total];
const literalVisible = [Object.keys(literal), JSON.stringify(literal)];
const definedVisible = [Object.keys(defined), JSON.stringify(defined)];
const instanceVisible = [Object.keys(instance), JSON.stringify(instance)];

const spreadLiteral = { ...literal };
const spreadShape = shape(spreadLiteral, 'total');
literal.fare = 900;
const gettersFollow = [literal.total, defined.total];
const snapshotDoesNot = spreadLiteral.total;

console.log('descriptors:', literalShape, definedShape, instanceShape);
console.log('literal    :', literalVisible);
console.log('defined    :', definedVisible);
console.log('instance   :', instanceVisible);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a literal getter is an own accessor, enumerable and configurable', literalShape, ['function', true, true]);
test('the same getter via defineProperty defaults to neither', definedShape, ['function', false, false]);
test('a class getter is on the prototype, so the instance owns nothing', [instanceShape, prototypeShape], ['no own property', ['function', false, true]]);
test('all three read identically, which is what hides the difference', allThreeRead, [450, 450, 450]);
test('so only the literal getter is listed and serialised', [literalVisible, definedVisible, instanceVisible], [[['fare', 'total'], '{"fare":400,"total":450}'], [['fare'], '{"fare":400}'], [['fare'], '{"fare":400}']]);
test('spread replaces the accessor with a plain data property', spreadShape, ['undefined', true, true]);
test('so the getters follow a later change to the fare', gettersFollow, [950, 450]);
test('while the spread copy is a snapshot, frozen at the moment it was taken', snapshotDoesNot, 450);

Three ways to write one getter, three different answers to "is this part of the object's data". The literal form is enumerable, so Object.keys, for...in, spread, Object.assign and JSON.stringify all include it — a derived value quietly becomes a stored field the moment anything serialises the object, and it comes back from the server as a real property that no longer recomputes.

defineProperty and the class form both keep it out, for different reasons: the first because the defaults are false, the second because prototype properties are never own properties of the instance. The fourth assertion is the reason this is worth an exercise — all three read as 450, so nothing at the call site tells you which kind you have.

The last three assertions are the one that bites in practice. Spread and Object.assign perform a [[Get]] per key, so an accessor becomes a data property holding whatever it returned at that instant. { ...literal } looks like a copy and is a snapshot: change fare and the original's total moves while the copy's does not. To copy an object with its accessors intact you need Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)), which is exactly what spread is not.

Also note defined.total is non-configurable, so it can never be redefined or deleted, and Trip.prototype.total is configurable, so it can. If you mean a getter to be part of the public data, write it in a literal; if you mean it as behaviour, put it on the prototype or define it explicitly.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.