Sub topic 3
Accessors with Object.defineProperty
Object literal syntax (get name() {}) is the easiest way to write a getter or setter. It only works while you are writing the object. Object.defineProperty lets you add an accessor to an object that already exists, including a prototype or an object someone else created. It also lets you control every attribute of the property. This chapter covers that API, its defaults, which differ from literal syntax, and the errors it throws.
This chapter assumes you know the difference between data and accessor properties, can read the output of Object.getOwnPropertyDescriptor, and understand how strict mode changes failed assignments.
The basic call
Object.defineProperty(obj, key, descriptor) creates or changes one property on obj and returns obj. An accessor descriptor can contain four fields:
| Field | Meaning | Default when omitted |
|---|---|---|
| `get` | Function called on read, with `this` set to the receiver | `undefined` |
| `set` | Function called on write, with the assigned value as its argument | `undefined` |
| `enumerable` | Shows up in `Object.keys`, `for...in`, spread, and `JSON.stringify` | `false` |
| `configurable` | Can be deleted or redefined later | `false` |
An accessor descriptor never contains value or writable. Those two fields belong to data descriptors.
The following example creates a read-only balance on an account object. The real number lives in a variable the outside world cannot reach.
'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
}Because the descriptor has no set, assigning to the property fails. In strict mode a failed assignment throws a TypeError. The code that owns the balance variable can still change it, and every later read of account.balance returns the new value.
The defaults are the opposite of literal syntax
This difference catches people most often. Literal getters and class-free object accessors are enumerable and configurable. With defineProperty, any attribute you leave out defaults to false.
const literal = {
get id() { return 42; }
};
const defined = {};
Object.defineProperty(defined, 'id', {
get() { return 42; }
});
const a = Object.getOwnPropertyDescriptor(literal, 'id');
const b = Object.getOwnPropertyDescriptor(defined, 'id');
console.log(a.enumerable, a.configurable); // true true
console.log(b.enumerable, b.configurable); // false false
console.log(Object.keys(literal)); // [ 'id' ]
console.log(Object.keys(defined)); // []
console.log(defined.id); // 42Both objects return 42 when you read id. The defined version is hidden from Object.keys, from spread, and from JSON.stringify. It also cannot be deleted or redefined. Sometimes that is exactly what you want, such as a hidden, locked helper property. More often it is an accident, so state enumerable and configurable explicitly every time.
What happens on read and write
The diagram shows how the engine handles an assignment to a property that is defined as an accessor, either on the object itself or anywhere on its prototype chain.
Notice the last box. A getter-only accessor on a prototype blocks assignment completely. The assignment does not create an own property that shadows it. To shadow it you must call defineProperty on the instance.
Silent failure in sloppy mode
ES modules and class bodies are always strict, so the TypeError is what you will usually see. Older scripts may still run in sloppy mode, where the same mistake does nothing and reports nothing. Run the following as a classic script, not as a module, to see both behaviors:
const o = {};
Object.defineProperty(o, 'x', {
get() { return 1; }
});
function sloppyAssign() {
o.x = 2; // ignored
return o.x;
}
function strictAssign() {
'use strict';
o.x = 2; // throws
}
console.log(sloppyAssign()); // 1
try {
strictAssign();
} catch (err) {
console.log(err instanceof TypeError); // true
}If a value "won't change" and nothing reports an error, check for a getter-only accessor and a sloppy-mode caller.
Invalid descriptors
defineProperty checks the descriptor before it changes anything. Each of the following throws a TypeError:
- Mixing accessor and data fields, such as
getwithvalueorsetwithwritable. - Giving
getorseta value that is neither a function norundefined. - Redefining a non-configurable property in a way that changes it.
- Calling it on a non-object, such as
Object.defineProperty(5, 'x', {}).
const attempts = [
{ value: 1, get() { return 2; } },
{ writable: true, set(v) {} },
{ get: 'not a function' }
];
for (const descriptor of attempts) {
try {
Object.defineProperty({}, 'x', descriptor);
} catch (err) {
console.log(err instanceof TypeError); // true, three times
}
}The exact error messages differ between engines, so test for the error type, not the message text.
Configurable: redefining, merging, and locking
On a configurable property, a second defineProperty call merges the new descriptor into the existing one. Fields you leave out stay as they were. You can add a setter later without losing the getter:
let celsius = 20;
const temp = {};
Object.defineProperty(temp, 'fahrenheit', {
get() { return celsius * 9 / 5 + 32; },
enumerable: true,
configurable: true
});
Object.defineProperty(temp, 'fahrenheit', {
set(f) { celsius = (f - 32) * 5 / 9; }
});
temp.fahrenheit = 212;
console.log(celsius); // 100
console.log(temp.fahrenheit); // 212
const d = Object.getOwnPropertyDescriptor(temp, 'fahrenheit');
console.log(typeof d.get, typeof d.set, d.enumerable); // function function trueOnce configurable is false, the property is locked. You can call defineProperty again with the identical get and set functions, and nothing changes. Passing a new function throws. Deleting returns false in sloppy mode and throws in strict mode.
const locked = {};
const getter = () => 'fixed';
Object.defineProperty(locked, 'tag', { get: getter });
Object.defineProperty(locked, 'tag', { get: getter }); // allowed: no change
try {
Object.defineProperty(locked, 'tag', { get: () => 'changed' });
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Reflect.deleteProperty(locked, 'tag')); // false
console.log(locked.tag); // 'fixed'Reflect.defineProperty takes the same arguments but returns true or false instead of throwing. Use it when failure is an expected outcome you want to branch on.
A self-replacing lazy getter
A configurable accessor can turn itself into a data property the first time it is read. The expensive work then runs once, and later reads are plain property lookups.
const config = {};
Object.defineProperty(config, 'settings', {
enumerable: true,
configurable: true, // required, or the redefinition below throws
get() {
console.log('computing...');
const value = { theme: 'dark', retries: 3 };
Object.defineProperty(this, 'settings', {
value,
writable: false,
enumerable: true,
configurable: false
});
return value;
}
});
console.log(config.settings.theme); // computing... then 'dark'
console.log(config.settings.theme); // 'dark' (no log)
console.log('get' in Object.getOwnPropertyDescriptor(config, 'settings')); // falseIf you put this getter on a prototype, this is the instance, so each instance gets its own cached data property and the prototype keeps the getter for other instances.
Adding accessors to prototypes
defineProperty can attach a computed property to every instance at once by putting it on a shared prototype. This is how you add accessors to constructor functions, which have no literal syntax for prototype members.
function Rect(width, height) {
this.width = width;
this.height = height;
}
Object.defineProperty(Rect.prototype, 'area', {
get() { return this.width * this.height; },
enumerable: false,
configurable: true
});
const r = new Rect(3, 4);
console.log(r.area); // 12
console.log(Object.hasOwn(r, 'area')); // false
console.log('area' in r); // true
console.log(JSON.stringify(r)); // {"width":3,"height":4}Making prototype accessors non-enumerable matches how class syntax defines methods and accessors, and it keeps for...in loops clean. Avoid doing this to built-in prototypes such as Array.prototype. Code you don't own can break in ways that are hard to trace.
Defining many properties at once
Object.defineProperties(obj, descriptors) takes an object that maps keys to descriptors. Object.create(proto, descriptors) accepts the same map as its second argument.
const point = Object.defineProperties({}, {
_x: { value: 3, writable: true },
_y: { value: 4, writable: true },
length: {
get() { return Math.hypot(this._x, this._y); },
enumerable: true
}
});
console.log(point.length); // 5
console.log(Object.keys(point)); // [ 'length' ]The same defaults apply here. _x and _y are non-enumerable because enumerable was not set.
Copying accessors without flattening them
Spread and Object.assign read each source property, so they call the getters and copy the results as plain values. To copy the accessors themselves, pair Object.getOwnPropertyDescriptors with Object.defineProperties:
const source = {
get now() { return Date.now(); }
};
const spreadCopy = { ...source };
const realCopy = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
console.log(typeof Object.getOwnPropertyDescriptor(spreadCopy, 'now').value); // 'number'
console.log(typeof Object.getOwnPropertyDescriptor(realCopy, 'now').get); // 'function'spreadCopy.now is frozen at the moment of copying. realCopy.now still returns the current time on every read.
Choosing between literal syntax and defineProperty
| Situation | Prefer |
|---|---|
| Writing a new object or class by hand | Literal or class `get`/`set` syntax |
| Adding an accessor to an existing object or prototype | `Object.defineProperty` |
| Hiding a property from enumeration and JSON | `defineProperty` with `enumerable: false` |
| Making a property permanent | `defineProperty` with `configurable: false` |
| Generating properties from data, such as a list of field names | `Object.defineProperties` in a loop or a built map |
| Handling definition failure without exceptions | `Reflect.defineProperty` |
Exercises
Exercise
You run Object.defineProperty(user, 'fullName', { get() { return this.first + ' ' + this.last; } }). Afterwards JSON.stringify(user) leaves out fullName, and delete user.fullName has no effect. Explain both results and give the corrected call.
Show answer
Attributes omitted from defineProperty default to false. enumerable: false hides fullName from JSON.stringify, and configurable: false prevents deletion. Corrected call: Object.defineProperty(user, 'fullName', { get() { return this.first + ' ' + this.last; }, enumerable: true, configurable: true }).
Exercise
A prototype defines a getter-only accessor id with configurable: true. In strict-mode code you run instance.id = 7. What happens, and how can you give that one instance its own id of 7?
Show answer
The assignment finds the inherited accessor, which has no setter, so it throws a TypeError and no own property is created. To shadow it, define an own property on the instance: Object.defineProperty(instance, 'id', { value: 7, writable: true, enumerable: true, configurable: true }).
Exercise
Why does Object.defineProperty({}, 'x', { get() { return 1; }, writable: false }) throw, even though writable is false?
Show answer
The presence of the writable field, whatever its value, makes this a data descriptor field. A descriptor cannot contain both accessor fields (get/set) and data fields (value/writable), so defineProperty throws a TypeError.