The syntax of the defineProperty()
method is:
Object.defineProperty(obj, prop, descriptor)
The defineProperty()
method, being a static method, is called using the Object
class name.
defineProperty() Parameters
The defineProperty()
method takes in:
- obj - The object on which to define the property.
- prop - The name or
Symbol
of the property to be defined or modified. - descriptor - The descriptor for the property being defined or modified.
Property descriptors present in objects are of two types: data descriptors and accessor descriptors. They can have the following optional properties.
configurable
enumerable
A data descriptors can also have:
value
writable
An accessor descriptors can also have:
get
set
Return value from defineProperty()
- Returns the object that was passed to the function.
Note:
- By default, values added using
Object.defineProperty()
are immutable and not enumerable. - If a descriptor has neither of
value
,writable
,get
andset
keys, it is treated as a data descriptor. If a descriptor has bothvalue
orwritable
andget
orset
keys, an exception is thrown.
Example: Adding a data property to object
let obj = {};
// with a data property descriptor
Object.defineProperty(obj, "property1", {
value: 788,
writable: true,
enumerable: true,
configurable: true,
});
console.log(obj.property1); // 788
// with an accessor property descriptor
Object.defineProperty(obj, "property2", {
get() {
console.log("Getting Value...");
return val;
},
set(newVal) {
console.log("Setting Value...");
val = newVal;
},
enumerable: true,
configurable: true,
});
obj.property2 = 6969; // Setting Value...
console.log(obj.property2); // 6969
Output
788 Setting Value... Getting Value... 6969
We cannot mix both data and accessor property descriptors as it would throw an error.
To modify a property, the object's writable
property has to be true
, else it won't modify and throw error in strict mode.
The enumerable
property attribute defines whether the property is picked by Object.assign()
or spread operator.
The configurable
attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than value
and writable
) can be changed.
Recommended Reading: Javascript Object defineProperties()