Understanding the getOwnPropertyDescriptors() Method in JavaScript
The getOwnPropertyDescriptors()
method of the Object
object in JavaScript allows us to retrieve all own (non-inherited) property descriptors of an object. By using this method, we can obtain a new object that provides a comprehensive list of descriptors.
Here’s an example to illustrate its usage:
1 | const dog = {} |
One key use case for this method arises from the limitations of Object.assign()
, introduced in ES2015. Object.assign()
allows us to copy enumerable own properties from one or more objects and create a new object. However, it fails to correctly copy properties with non-default attributes.
Consider the following object:
1 | const person1 = { |
Attempting to copy this object using Object.assign()
will not work:
1 | const person2 = {} |
However, by using Object.defineProperties()
along with Object.getOwnPropertyDescriptors()
, we can successfully copy the object and preserve the setter:
1 | const person3 = {} |
Let’s run a console test to verify the results:
1 | person1.name = 'x' |
As we can see, person2
does not have the setter since it was not copied over correctly.
The same limitation applies when shallow cloning objects with Object.create()
.
tags: [“JavaScript”, “Object”, “getOwnPropertyDescriptors”, “property descriptors”, “object cloning”]