Add Methods After Inheritance alternate way

I have solved the challenge with standard way by defining each prototype object separately, But I want to ask if there are more prototype objects to be added to Dog how can I modify this to work properly. As in current scenario, it gives this error

Woof!
TypeError: beagle.eat is not a function

function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };

function Dog() { }

// Only change code below this line
Dog.prototype= Object.create(Animal.prototype);
Dog.prototype={
  constructor: Dog,
  bark: ()=> {
    console.log("Woof!");
  }
}

// Only change code above this line

let beagle = new Dog();
beagle.bark();
beagle.eat();

LInk to Challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance

This code says make the prototype of Dog that of Animal, which means Dog is going to inherit the method eat() from animal.

This code is setting the prototype of Dog to what’s after the assignment operator.
The problem here is remember you have set the prototype of Dog in you first code to be that of Animal already, so the second code overrides the first. implying you will get the bark method which you defined on this prototype but the eat method defined on the animal prototype will not be available to you hence the error beagle.eat is not a function.
so get rid of the second code and simply add the bark method to Dogs prototype since its already defined.
Dog.prototype.methodYouWant = () => console.log("value")
by using Object .create, Dogs constructor is overritten to that of Animal so you need to set it back to Dog
Dog.prototype.constructor = Dog

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.