Object.getOwnPropertyDescriptors()
This chapter explains the ECMAScript 2017 feature “Object.getOwnPropertyDescriptors()
” by Jordan Harband and Andrea Giammarchi.
Object.getOwnPropertyDescriptors(obj)
returns the property descriptors of all own properties of obj
, in an Array:
Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors(obj)
accepts an object obj
and returns an object result
:
obj
, it adds a property to result
whose key is the same and whose value is the the former property’s descriptor.Property descriptors describe the attributes of a property (its value, whether it is writable, etc.). For more information, consult Sect. “Property Attributes and Property Descriptors” in “Speaking JavaScript”.
This is an example of using Object.getOwnPropertyDescriptors()
:
This is how you would implement Object.getOwnPropertyDescriptors()
:
Object.getOwnPropertyDescriptors()
Since ES6, JavaScript already has a tool method for copying properties: Object.assign()
. However, this method uses simple get and set operations to copy a property whose key is key
:
That means that it doesn’t properly copy properties with non-default attributes (getters, setters, non-writable properties, etc.). The following example illustrates this limitation. The object source
has a setter whose key is foo
:
Using Object.assign()
to copy property foo
to object target
fails:
Fortunately, using Object.getOwnPropertyDescriptors()
together with Object.defineProperties()
works:
Shallow cloning is similar to copying properties, which is why Object.getOwnPropertyDescriptors()
is a good choice here, too.
This time, we use Object.create()
that has two parameters:
Object.getOwnPropertyDescriptors()
.The syntactically nicest way of using an object literal to create an object with an arbitrary prototype prot
is to use the special property __proto__
:
Alas, that feature is only guaranteed to be there in browsers. The common work-around is Object.create()
and assignment:
But you can also use Object.getOwnPropertyDescriptors()
:
Another alternative is Object.assign()
:
super
A method that uses super
is firmly connected with its home object (the object it is stored in). There is currently no way to copy or move such a method to a different object.