9.9 API: property descriptors
The following tool methods use property descriptors:
Object.defineProperty(obj: object, key: string|symbol, propDesc: PropertyDescriptor): object
[ES5]Creates or changes a property on
obj
whose key iskey
and whose attributes are specified viapropDesc
. Returns the modified object.const obj = {};
const result = Object.defineProperty(
obj, 'happy', {
value: 'yes',
writable: true,
enumerable: true,
configurable: true,
});
// obj was returned and modified:
assert.equal(result, obj);
assert.deepEqual(obj, {
happy: 'yes',
});
Object.defineProperties(obj: object, properties: {[k: string|symbol]: PropertyDescriptor}): object
[ES5]The batch version of
Object.defineProperty()
. Each propertyp
of the objectproperties
specifies one property that is to be added toobj
: The key ofp
specifies the key of the property, the value ofp
is a descriptor that specifies the attributes of the property.const address1 = Object.defineProperties({}, {
street: { value: 'Evergreen Terrace', enumerable: true },
number: { value: 742, enumerable: true },
});
Object.create(proto: null|object, properties?: {[k: string|symbol]: PropertyDescriptor}): object
[ES5]First, creates an object whose prototype is
proto
. Then, if the optional parameterproperties
has been provided, adds properties to it – in the same manner asObject.defineProperties()
. Finally, returns the result. For example, the following code snippet produces the same result as the previous snippet:const address2 = Object.create(Object.prototype, {
street: { value: 'Evergreen Terrace', enumerable: true },
number: { value: 742, enumerable: true },
});
assert.deepEqual(address1, address2);
Object.getOwnPropertyDescriptor(obj: object, key: string|symbol): undefined|PropertyDescriptor
[ES5]Returns the descriptor of the own (non-inherited) property of
obj
whose key iskey
. If there is no such property,undefined
is returned.assert.deepEqual(
Object.getOwnPropertyDescriptor(Object.prototype, 'toString'),
{
value: {}.toString,
writable: true,
enumerable: false,
configurable: true,
});
assert.equal(
Object.getOwnPropertyDescriptor({}, 'toString'),
undefined);
Object.getOwnPropertyDescriptors(obj: object): {[k: string|symbol]: PropertyDescriptor}
[ES2017]Returns an object where each property key
'k'
ofobj
is mapped to the property descriptor forobj.k
. The result can be used as input forObject.defineProperties()
andObject.create()
.``` const propertyKey = Symbol(‘propertyKey’); const obj = {
[propertyKey]: 'abc',
get count() { return 123 },
};
const desc = Object.getOwnPropertyDescriptor.bind(Object);
assert.deepEqual(
Object.getOwnPropertyDescriptors(obj),
{
[propertyKey]: {
value: 'abc',
writable: true,
enumerable: true,
configurable: true
},
count: {
get: desc(obj, 'count').get, // (A)
set: undefined,
enumerable: true,
configurable: true
}
});
```
Using `desc()` in line A is a work-around so that `.deepEqual()` works.