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.

  1. Data descriptor:
  2. Value: the value of an attribute.
  3. Is the value of the writable property writable (true/false)?
  4. Is the enumerable property of the object true or false, i.e. can it be traversed through a for…in loop?
  5. Configurable: Specifies whether the property can be modified or deleted (true/false).
  6. Accessor descriptors:
  7. Getter function of the attribute ‘get’, called when retrieving the attribute value.
  8. setter function of the property, called when setting the property value.
  9. enumerable: whether the property is enumerable.
  10. 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.

广告
Closing in 10 seconds
bannerAds