Sometimes, we want to use JavaScript Object.defineProperty method.
In this article, we’ll look at how to use JavaScript Object.defineProperty method.
How to use JavaScript Object.defineProperty method?
To use JavaScript Object.defineProperty method, we can call it with the object we want to add a property to, the property name, and an object with properties to configure the property.
For instance, we write
const employee = {
firstName: "jane",
lastName: "smith",
};
Object.defineProperty(employee, "toString", {
value() {
return `${this.firstName} ${this.lastName}`;
},
writable: true,
enumerable: true,
configurable: true,
});
console.log(employee.toString());
to call Object.defineProperty
with employee
to add the toString
method to it.
We define its value as a getter that returns the firstName
and lastName
properties combined.
And then we set writable
to true
. to let us reassign it.
enumerable
is true
means we can return its value with Object.keys
, Object.values
, etc.
And configurable
set to true
means we can change the object’s configurability, writability and enumerability.
Conclusion
To use JavaScript Object.defineProperty method, we can call it with the object we want to add a property to, the property name, and an object with properties to configure the property.