Object.defineProperty(obj, prop, descriptor)
This method allows a precise addition to or modification of a property on an object. By default, properties added using Object.defineProperty()
are not writable, not enumerable, and not configurable.
const obj = {}; Object.defineProperty(obj, 'key2', { configurable: false, enumerable: false, value: 'static', writable: false }); const obj2 = {}; let bValue = 38; Object.defineProperty(obj2, 'b', { get() { return bValue; }, set(newValue) { bValue = newValue; }, enumerable: true, configurable: true });
Data descriptor vs accessor descriptor
A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys:
Description | default when using defineProperty | default when using const obj = { } | |
configurable | if false, then the type of this property cannot be changed between data property and accessor property, the property may not be deleted, other attributes of its descriptor cannot be changed, however, if it’s a data descriptor with writable: true , the value can be changed, and writable can be changed to false | false | true |
enumerable | Whether the property shall appear during for...in loop or Object.keys method and whether the property is picked by Object.assign() or spread operator. You can check with myObj.propertyIsEnumerable('a') | false | true |
value | any valid JavaScript value | undefined | |
writable | if property can be changed with obj.foo = "new"; | false | true |
get | Accessor descriptor only. A function which serves as a getter for the property, or undefined if there is no getter. | ||
set | Accessor descriptor only. A function which serves as a setter for the property, or undefined if there is no setter. |
If a descriptor has neither of value
, writable
, get
and set
keys, it is treated as a data descriptor. If a descriptor has both [value
or writable
] and [get
or set
] keys, an exception is thrown.
More examples on the MDN website.
Object descriptors in decorators
Object descriptors play an important role in TypeScript decorators.