Object getOwnPropertyDescriptors() method

Find all information about the JavaScript getOwnPropertyDescriptors() method of the Object object

This method returns all of the object's own (non-inherited) property descriptors.

Object.getOwnPropertyDescriptors(obj)Accepts an object and returns a new object that provides a list of descriptors.

example:

const dog = {}
Object.defineProperties(dog, {
  breed: {
    value: 'Siberian Husky'
  }
})
Object.getOwnPropertyDescriptors(dog)
/*
{
  breed: {
    value: 'Siberian Husky',
    writable: false,
    enumerable: false,
    configurable: false
  }
}
*/

There is a use case that makes this property very useful. ES2015 gave usObject.assign(), It copies all enumerable properties from one or more objects and returns a new object. However, this has a problem because it cannot copy properties with non-default properties correctly.

For example, if an object has only one setter, it cannot be usedObject.assign(). For example with this object:

const person1 = {
  set name(newName) {
    console.log(newName)
  }
}

This copy attempt will be invalid:

const person2 = {}
Object.assign(person2, person1)

But this works and is copied to the setter correctly:

const person3 = {}
Object.defineProperties(person3,
  Object.getOwnPropertyDescriptors(person1))

You can see through the console test:

person1.name = 'x'
"x"

person2.name = ‘x’

person3.name = ‘x’ “x”

person2Missed the setter, it was not copied.

The same restriction applies to shallow cloned objects with the following characteristics:Object.create().

Download mine for freeJavaScript beginner's manual


More js tutorials: