I passed an object as the second parameter in the Object.create
method, but I'm getting the following error:
Uncaught TypeError: Property description must be an object: 1
Here's the faulty code:
var test = Object.create(null, {
ex1: 1,
ex2: 2,
meth: function () {
return 10;
},
meth1: function () {
return this.meth();
}
});
Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions.
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.
Object.create(proto, props)
has two arguments:
proto
— the object which should be the prototype of the newly-created object.props
(optional) — an object whose properties specify property descriptors to be added to the newly-created object, with the corresponding property names.
The format for the props
object is defined here.
In short, the available options for each property descriptor are these:
{
configurable: false, // or true
enumerable: false, // or true
value: undefined, // or any other value
writable: false, // or true
get: function () { /* return some value here */ },
set: function (newValue) { /* set the new value of the property */ }
}
The problem with your code is that the property descriptors you've defined are not objects.
Here's an example of a proper usage of property descriptors:
var test = Object.create(null, {
ex1: {
value: 1,
writable: true
},
ex2: {
value: 2,
writable: true
},
meth: {
get: function () {
return 'high';
}
},
meth1: {
get: function () {
return this.meth;
}
}
});
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