Reputation: 1195
I'm trying to use the properties object parameter in Object.create, the mdn says you pass an object into it, but when I pass an object into it I get an error telling me to passing an object, I'm confused as to what I'm doing wrong
let mammal={hasFur:true}
let dog=Object.create(mammal,{legs:4});//returns Uncaught TypeError: Property description must be an object: true at Function.create (<anonymous>)
Upvotes: 1
Views: 114
Reputation: 2777
In a simple definition, Object.create(proto[, propertiesObject]) is a mean for defining the abstract for object's properties, or defining specification of object's properties. It works like abstract classes
in some of the other languages, & not a specific object
.
It is not there to necessarily provide a default value for the props of the object being created. You have provided a literal (4) only, which is obviously not an object having the ability to describe specification for the property. We will see here, that 4 in its own is(even not necessarily) only a part of properties object for legs.
Now. with this in mind lets try to create your dog
object using Object.create()
. Here we go:
legs
.legs
to be enumerable while enumerating the object. we don't want to let others to change it with assignment operator. & also we want to default to 4.legs
property, we need a Property Descriptor to define it.[the second parameter of Object.defineProperties(obj, props)
]The props
mentioned above is second{& optional} parameter in Object.create(proto[, propertiesObject])
& has some keys for describing properties of objects:
props {configurable, enumerable, value, writable, get, set}
Lets code the dog
object:
let dog=Object.create(mammal,{
legs:{
enumerable : true,
writable : false,
value : 4 }
});
For more clarification, reading both of the references linked above, is highly helpful.
Upvotes: 2
Reputation: 943547
You've described legs
as 4
, and 4
is not an object.
See the MDN documentation which includes examples of the sorts of things you can assign there:
o = Object.create(Object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' },
In this example we use foo
instead of legs
. The value of an object, which includes a value
property holding the default value for foo
.
Upvotes: 3