JavaScriptFundamental (ES6), part 1
Object.defineProperty, enumerable and writable in JavaScript
148 getters, setters, and what enumerable false hides
hardDefine one non-enumerable, non-writable data property and one accessor property with a getter and a setter on the same object. Then report what each of Object.keys, JSON.stringify, spread, Object.getOwnPropertyNames and in can see. Show that spread flattens a getter into a dead value, that the setter can write back through another property, that defineProperty defaults every flag to false where an assignment defaults them to true, and what writing to a non-writable or getter-only property does under strict mode.
Stuck? Three hints, smallest first
- 1. A descriptor is either a data descriptor (
value,writable) or an accessor one (get,set). Never both, and the two never mix. - 2.
JSON.stringify,Object.keysand spread all skip non-enumerable properties.Object.getOwnPropertyNamesdoes not, so this is not privacy. - 3. A getter is a function call, so serialising or spreading INVOKES it and stores whatever it returned at that moment.
let getterCalls = 0;
let setterCalls = 0;
const order = { item: 'gari', qty: 3 };
Object.defineProperty(order, 'unitKobo', {
value: 120000, enumerable: false, writable: false, configurable: false,
});
Object.defineProperty(order, 'totalNaira', {
get() { getterCalls += 1; return (this.qty * this.unitKobo) / 100; },
set(naira) { setterCalls += 1; this.qty = Math.round((naira * 100) / this.unitKobo); },
enumerable: true,
configurable: true,
});
const visible = Object.keys(order);
const everything = Object.getOwnPropertyNames(order);
const json = JSON.parse(JSON.stringify(order));
const callsAfterJson = getterCalls;
const snapshot = { ...order };
order.qty = 10;
const liveVersusSnapshot = [order.totalNaira, snapshot.totalNaira];
order.totalNaira = 7200; // the setter writes back through qty
const afterSetter = [setterCalls, order.qty, order.totalNaira];
let writeError;
try { order.unitKobo = 1; writeError = 'no throw'; } catch (e) { writeError = e.constructor.name; }
let deleteError;
try { delete order.unitKobo; deleteError = 'no throw'; } catch (e) { deleteError = e.constructor.name; }
let redefineError;
try { Object.defineProperty(order, 'unitKobo', { value: 2 }); redefineError = 'no throw'; }
catch (e) { redefineError = e.constructor.name; }
const defined = {};
Object.defineProperty(defined, 'x', { value: 1 });
const assigned = {};
assigned.x = 1;
const definedFlags = Object.getOwnPropertyDescriptor(defined, 'x');
const assignedFlags = Object.getOwnPropertyDescriptor(assigned, 'x');
let definedWrite;
try { defined.x = 2; definedWrite = 'no throw'; } catch (e) { definedWrite = e.constructor.name; }
const readOnly = {};
Object.defineProperty(readOnly, 'label', { get() { return 'fixed'; }, enumerable: true, configurable: true });
let getterOnlyWrite;
try { readOnly.label = 'other'; getterOnlyWrite = 'no throw'; } catch (e) { getterOnlyWrite = e.constructor.name; }
const accessor = Object.getOwnPropertyDescriptor(order, 'totalNaira');
const accessorShape = [Object.keys(accessor).sort(), typeof accessor.get, 'value' in accessor, 'writable' in accessor];
const reachability = ['unitKobo' in order, Object.hasOwn(order, 'unitKobo'), order.unitKobo];
console.log('visible :', visible, '| all own names:', everything);
console.log('json :', json, '| getter calls:', callsAfterJson);
console.log('snapshot :', snapshot, '| live vs snapshot:', liveVersusSnapshot);
console.log('setter :', afterSetter);
console.log('strict :', writeError, deleteError, redefineError, definedWrite, getterOnlyWrite);
console.log('flags :', definedFlags, assignedFlags);
console.log('accessor :', accessorShape, '| reachable:', reachability);
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('enumerable false hides the key from Object.keys, JSON and spread alike', [visible, Object.keys(json), Object.keys(snapshot)], [['item', 'qty', 'totalNaira'], ['item', 'qty', 'totalNaira'], ['item', 'qty', 'totalNaira']]);
test('but getOwnPropertyNames and in still see it, so this is not privacy', [everything, reachability], [['item', 'qty', 'unitKobo', 'totalNaira'], [true, true, 120000]]);
test('a getter is invoked while serialising, so a computed field lands in the JSON', [json.totalNaira, callsAfterJson], [3600, 1]);
test('spread flattens the getter into a plain value that then stops tracking', liveVersusSnapshot, [12000, 3600]);
test('the setter intercepts assignment and can write back through another property', afterSetter, [1, 6, 7200]);
test('defineProperty defaults every flag to false; an assignment defaults them to true', [definedFlags, assignedFlags], [{ value: 1, writable: false, enumerable: false, configurable: false }, { value: 1, writable: true, enumerable: true, configurable: true }]);
test('so under strict mode writing, deleting or redefining it all throw', [writeError, deleteError, redefineError, definedWrite], ['TypeError', 'TypeError', 'TypeError', 'TypeError']);
test('and a getter with no setter throws on assignment rather than ignoring it', [getterOnlyWrite, readOnly.label], ['TypeError', 'fixed']);
test('an accessor descriptor carries get and set, and never value or writable', accessorShape, [['configurable', 'enumerable', 'get', 'set'], 'function', false, false]);
Every property is a descriptor, and there are two kinds. A data property has value and writable; an accessor property has get and set. They are mutually exclusive, which is why the accessor descriptor above has no value key at all rather than an undefined one. An accessor property looks exactly like a field from the outside and is a function call underneath, so it can validate, compute, log or refuse.
enumerable: false is presentation, not protection. It removes the key from Object.keys, Object.values, Object.entries, for...in, spread, Object.assign and JSON.stringify — which is genuinely useful for keeping an internal field out of an API response — while Object.getOwnPropertyNames, Object.getOwnPropertyDescriptors, Reflect.ownKeys and in report it happily. For real privacy use a #field or a closure.
The spread assertion is the trap worth carrying away. { ...order } does not copy the getter, it calls it once and stores the number, so the copy is a snapshot that silently stops tracking while the original keeps recomputing. The same is true of Object.assign and of JSON.stringify; only Object.defineProperties with Object.getOwnPropertyDescriptors clones the behaviour rather than the result. And note how much stricter defineProperty is than an assignment: omit the flags and you get a frozen, hidden, permanent property, which under "use strict" turns the next innocent write into a TypeError instead of the silent no-op sloppy mode gave you.