21
loading...
This website collects cookies to deliver better user experience
Object.create
. Let's have a look at an example. For the example code, we will use the animal
and dog
taxonomy, where animal is a prototype of dog.const animal = {
eat: function() {
console.log(this.name + ' eats');
},
};
const dog = Object.create(animal, {
bark: {
value: function() {
console.log(this.name + ' woofs');
},
},
});
const henry = Object.create(dog, {
name: { value: 'Henry' },
});
henry.bark();
henry.eat();
Object.create
function takes two arguments. First one is the desired prototype of the object being created, and the second one is the properties you want to add or the Properties Descriptor Object
, it's optional.Object.create
is dog. So the full prototype chain ist:Object.getOwnPropertyDescriptor
can be used to get a property descriptor on any object. To describe the value of a property, the descriptor can either use value or get and set to create a property getter/setter. The other properties are associated meta-data for the property. There is a writable property that determines whether the property can be reassigned, and a enumerable property, which determines whether the property will be enumerated in property iterator abstractions (like Object.keys). The configurable property sets whether the property descriptor itself can be altered. The default for all of these meta-data keys is false. Read more about property descriptors at MDN.henry.eat
is called.