I am creating a object using Object.create
and I want to add properties to it.
> var o = Object.create({}); undefined > Object.defineProperty(o, "foo", {value: 43, enumerable: true}); {foo: 43} > o {foo: 43} > o.foo 43 > for (var i in o) { console.log(i); } foo > Object.keys(o) ['foo'] > Object.defineProperty(o, "foo", {value: 43, enumerable: false }); TypeError: Cannot redefine property: bar
Q1) Why can't I redefine the property ?
> o.__proto__ {} > o.prototype undefined
Q2) Why is the prototype empty ? And why are these 2 values different i.e. {}
vs undefined
?
the type of this property cannot be changed between data property and accessor property, and. the property may not be deleted, and. other attributes of its descriptor cannot be changed (however, if it's a data descriptor with writable: true , the value can be changed, and writable can be changed to false ).
Syntax: Object. defineProperty(obj, prop, descriptor)
You are unable to redefine the property because Object.defineProperty()
defaults to non-configurable properties, from the docs:
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.
So this defaults to false - you'd need to pass it configurable: true
to allow it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With