Sub topic 3
Accessors with Object.defineProperty
This chapter assumes you know how property descriptors separate data properties from accessor properties, and that you have written getters and setters in object literals. It also uses closures and strict mode.
Object literal syntax only works when you create the object. Object.defineProperty lets you add an accessor to an object that already exists. It also lets you choose the descriptor flags yourself, so you can make an accessor hidden from enumeration or lock it against redefinition.
The basic call
Object.defineProperty(obj, key, descriptor) takes the target object, the property name, and a descriptor. An accessor descriptor can contain get, set, enumerable, and configurable.
'use strict';
let balance = 0;
const account = {};
Object.defineProperty(account, 'balance', {
get() { return balance; },
enumerable: true,
configurable: false
});
console.log(account.balance); // 0
try {
account.balance = 50; // no setter defined
} catch (err) {
console.log(err instanceof TypeError); // true
}The getter reads balance from the surrounding scope, so code outside the closure can't change it through account. Because the property has no set, it is read-only. In strict mode, assigning to it throws a TypeError. In sloppy mode, the same assignment fails silently and account.balance stays 0, which makes bugs harder to find. ES modules and class bodies always run in strict mode.
Defaults differ from literal syntax
When defineProperty creates a new property, any flag you leave out defaults to false. Literal getters and setters default to true.
| Flag | Literal `get x() {}` | `defineProperty` (omitted) |
|---|---|---|
| `enumerable` | `true` | `false` |
| `configurable` | `true` | `false` |
| `get` / `set` | as written | `undefined` |
const config = {};
Object.defineProperty(config, 'mode', {
get() { return 'production'; }
});
console.log(config.mode); // 'production'
console.log(Object.keys(config)); // []
const d = Object.getOwnPropertyDescriptor(config, 'mode');
console.log(d.enumerable, d.configurable); // false falseThis is the most common surprise with defineProperty. The property works, but it is missing from Object.keys, for...in, and object spread. If you want it to show up there, set enumerable: true explicitly.
Accessor or data, never both
A descriptor describes either an accessor or a data property. If it contains get or set together with value or writable, the call throws.
try {
Object.defineProperty({}, 'x', {
get() { return 1; },
value: 2
});
} catch (err) {
console.log(err instanceof TypeError); // true
}Several accessors at once
Object.defineProperties takes a map of names to descriptors. It works well in factory functions, where closure variables hold the state:
function createRange(min, max) {
const range = {};
Object.defineProperties(range, {
min: { get() { return min; }, enumerable: true },
max: { get() { return max; }, enumerable: true },
span: {
get() { return max - min; },
set(value) { max = min + value; },
enumerable: true
}
});
return range;
}
const r = createRange(10, 15);
console.log(r.span); // 5
r.span = 20;
console.log(r.max); // 30
console.log(Object.keys(r)); // [ 'min', 'max', 'span' ]Locking with configurable: false
If a property has configurable: false, you can't delete it or redefine it. A later defineProperty call that changes its getter throws a TypeError. Use this for properties that must never be replaced. Keep in mind that the lock is permanent for that object.
Exercise
You run Object.defineProperty(user, 'fullName', { get() { return this.first + ' ' + this.last; } }) on an existing object. Why is fullName missing from JSON.stringify(user) and Object.keys(user), and how do you fix it?
Show answer
When defineProperty creates a property, omitted flags default to false, so enumerable is false. Object.keys and JSON.stringify skip non-enumerable properties. Add enumerable: true to the descriptor. JSON.stringify calls the getter for enumerable own accessors, so fullName then appears in the output.
Exercise
What happens if you pass { get() { return 1; }, writable: true } to Object.defineProperty?
Show answer
It throws a TypeError, because a descriptor can't mix accessor keys (get, set) with data keys (value, writable).