I'm learning about objects, prototypes and inheritances. I got a doubt regarding the following code, from a conceptual viewpoint:
function Animal() {
this.eat = function() {
console.log("nom nom nom");
}
};
const dog = new Animal();
const cat = Object.create(Animal);
dog.eat(); // nom nom nom
cat.eat(); // cat.eat is not a function
This doesn't work either:
const cat = Object.create(Animal.prototype);
cat.eat(); // cat.eat is not a function
The only way to make it work on cat
is to assign the function to Animal.prototype.eat on a separate line.
As I read on this thread, new Animal
is essentially Object.create(Animal.prototype)
. So, why is dog
inheriting the eat
function (which, I understand, is an 'Own Property' of the Animal constructor) and cat isn't, even when created with Animal.prototype
as its parameter?
Thanks a lot in advance!