The following code does not appear to copy over an object's prototype.
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
function animalCreator(proto, attributes) {
return {...Object.create(proto), ...attributes}
}
const cat = animalCreator(animalProto, { name: 'garfield' })
cat.eat() // this is an error; function is not defined; it doesn't appear to link the prototype chain.
If I replace the spread with the following it works:
return Object.assign(Object.create(proto), attributes)
Essentially my question is why does Object.assign
work but not the spread operator. Is there something Object.assign
is doing that the spread operator is missing?