Being a beginner in javascript, i tried to understand Object.create() method from here
https://developer-new.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
In the example code, line 18. A accessor property is created with writable set to true. I also read that writable is only for data descriptors.
Tried running,
var o = Object.create(Object.prototype, {
// foo is a regular "value property"
foo: {
writable:true, configurable:true, value: "hello"
},
// bar is a getter-and-setter (accessor) property
bar: {
writable: true,
configurable: false,
get: function() { return 10 },
set: function(value) { console.log("Setting `o.bar` to", value) }
}
});
console.log(o);
I get invalid property error
.
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Once an object is created, you can assign property values and invoke methods just like any other object. Function objects can also be created as part of an object literal. Below we create an object named circle with a property named area which is a function object.
The issue is that writable
and set
/get
are mutually exclusive. The code generates this helpful error in Chrome:
Invalid property. A property cannot both have accessors and be writable...
This makes some logical sense: if you have set
/get
accessors on a property, that property is never going to be written to and/or read from, because any attempts to read/write it will be intercepted by the accessor functions. If you define a property as writable
and give it accessor functions, you are simultaneously saying:
The error is simply stopping you from specifying a contradiction. I assume from the fact that you wrote a getter and setter, you don't really want the property to be writable
. Just remove that line, and your code runs perfectly.
Late answer, not looking for votes, but hoping this will be helpful.
There are two kinds of properties. Each property is EITHER:
a data property which has these four attributes:
OR an accessor property which has these four attributes:
Therefore there is no property that can have both get
and writable
. That's just the way JavaScript is! Please see section 8.6 of the ECMAScript Standard for the gory details.
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