I'm wondering when I should use
Object.defineProperty
to create new properties for an object. I'm aware that I'm able to set things like
enumerable: false
but when do you need this really? If you just set a property like
myObject.myprop = 5;
its descriptors are all set to true, right? I'm actually more curious when you guys use that rather verbose call to .defineProperty() and for what reasons.
Object.defineProperty
is mainly used to set properties with specific property descriptors (e.g. read-only (constants), enumerability (to not show a property in afor (.. in ..)
loop, getters, setters).Example
This method extends the
Object
prototype with a property. Only the getter is defined, and the enumerability is set tofalse
.