Object.defineProperty()
Defines a new property or modifies an existing one with a descriptor.
Syntax
Object.defineProperty(obj, prop, descriptor) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
obj | object | Yes | The object on which to define the property. |
prop | string | symbol | Yes | The name of the property to define or modify. |
descriptor | object | Yes | A data descriptor (value, writable) or accessor descriptor (get, set), plus enumerable and configurable. |
Returns
object — The object that was passed in.
Throws
TypeError— the descriptor is invalid or the property is non-configurable.
Examples
const o = {};
Object.defineProperty(o, 'x', { value: 42, enumerable: false });
console.log(o.x, Object.keys(o));
Output
42 []
const o = {};
Object.defineProperty(o, 'full', { get() { return 'computed'; } });
console.log(o.full);
Output
computed
Notes
Defaults for omitted attributes are false (writable, enumerable, configurable)
unlike normal assignment which makes them true. Use `defineProperties` to add
several at once.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 5 |
| firefox | 4 |
| safari | 5.1 |
| edge | 12 |
| node | 0.10 |