Hi there, please help me understand this.
function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype = {
constructor : Dog,
bark(){
console.log( "Woof!");
}
}
let beagle = new Dog();
console.log(beagle.eat());
The above-written code generates a TypeError: beagle.eat is not a function.
But when I write the same code as this
function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function (){
console.log("Woof!");
}
let beagle = new Dog();
console.log(beagle.eat());
It works absolutely fine.
My question is that why inheritance doesn’t work in the former case???
Link to this challenge - https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance
Reason for my confusion –
I want to know if I have to add several methods unique to the Dog Object, do I have to write each unique methods separately like this?
Dog.prototype.bark = function (){
console.log("Woof!");
}
Dog.prototype.method2 = function (){
console.log("Woof!");
}
Dog.prototype.method3 = function (){
console.log("Woof!");
}
Dog.prototype.method4 = function (){
console.log("Woof!");
}
I had read in an earlier chapter that
A more efficient way is to set the `prototype` to
a new object that already contains the properties.
This way, the properties are added all at once
How could I use inheritance as well as set the prototype to a new object in this case?