How to get property descriptors of an object in JavaScript ?
In JavaScript, we can get the property descriptors of an object using the Object.getOwnPropertyDescriptor()
method. This method takes two parameters: the object and the property name. It returns an object that contains the property descriptor of the specified property.
Here's an example:
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
const [firstName, lastName] = name.split(' ');
this.firstName = firstName;
this.lastName = lastName;
}
};
const descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log(descriptor);
Output:
{
value: 'John',
writable: true,
enumerable: true,
configurable: true
}
In this example, we have an object person
with three properties: firstName
, lastName
, and fullName
. We use the Object.getOwnPropertyDescriptor()
method to get the property descriptor of the firstName
property and log it to the console.
The output shows that the firstName
property has a value of 'John'
, is writable, enumerable, and configurable.
We can also use the Object.getOwnPropertyDescriptors()
method to get the property descriptors of all properties of an object. This method takes one parameter: the object. It returns an object that contains the property descriptors of all properties of the specified object.
Here's an example:
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
const [firstName, lastName] = name.split(' ');
this.firstName = firstName;
this.lastName = lastName;
}
};
const descriptors = Object.getOwnPropertyDescriptors(person);
console.log(descriptors);
Output:
{
firstName: {
value: 'John',
writable: true,
enumerable: true,
configurable: true
},
lastName: {
value: 'Doe',
writable: true,
enumerable: true,
configurable: true
},
fullName: {
get: [Function: get fullName],
set: [Function: set fullName],
enumerable: true,
configurable: true
}
}
In this example, we use the Object.getOwnPropertyDescriptors()
method to get the property descriptors of all properties of the person
object and log them to the console.
The output shows that the firstName
and lastName
properties have values of 'John'
and 'Doe'
, respectively, and are writable, enumerable, and configurable. The fullName
property has a getter and a setter function, is enumerable, and configurable.