Introduction to JavaScript Object Property Descriptors
The property descriptor in JavaScript is an object used to describe the characteristics of an object property. Each object property has a set of attributes, such as: writability, enumerability, configurability, and value.
There are two types of property descriptors: data descriptors and accessor descriptors.
- Data descriptor:
- Value: the value of an attribute.
- Is the value of the writable property writable (true/false)?
- Is the enumerable property of the object true or false, i.e. can it be traversed through a for…in loop?
- Configurable: Specifies whether the property can be modified or deleted (true/false).
- Accessor descriptors:
- Getter function of the attribute ‘get’, called when retrieving the attribute value.
- setter function of the property, called when setting the property value.
- enumerable: whether the property is enumerable.
- configurable: whether the property can be modified.
You can use the method Object.getOwnPropertyDescriptor(obj, prop) to obtain the property descriptor. For example:
const obj = {
name: 'John',
age: 25
};
const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(descriptor);
The output is:
{
value: 'John',
writable: true,
enumerable: true,
configurable: true
}
This example demonstrates how to get the property descriptor of an object. It can be seen that the ‘name’ property is writable, enumerable, and configurable.