Set the Child's Prototype to an Instance of the Parent A few questions

Tell us what’s happening:

Why should Animal.prototype inherit its properties to Dog.prototype? Why wouldn’t it be right to inherit its properties to Dog?

I have already understood what prototypes are and how they work but in this case, what is the difference with using the Dog builder instead of using the Dog.prototype?
Why do we work so much with the builder’s prototype instead of using the builder?

Dog.prototype = Object.create(Animal.prototype);

Animal.prototype is used here because Object.create() creates objects using objects, not builders, correct?

I think that’s a lot of questions, I appreciate your help, sorry for the inconvenience.

Your code so far


function Animal() { }

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

function Dog() { }

// Add your code below this line
Dog.prototype = Object.create(Animal.prototype);

let beagle = new Dog();
beagle.eat();  // Should print "nom nom nom"

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36.

Challenge: Set the Child’s Prototype to an Instance of the Parent

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent

1 Like

Constructor I think is what OP means?

@ovirex , it’s using Object.create to be explicit about how JS works w/r/t inheritence (in practice you would probably use class Dog extends Animal, but that’s going to be doing the same thing under the hood)

1 Like

If Dog inherited properties directly, rather than into Dog.prototype (which you totally can do), you’re making a copy of those properties (methods or variables) directly in each instance of Dog. This could be a significant memory and performance hit.

By assigning Dog.prototype to Animal.prototype, we’re telling the Dog instances to use the properties from Animal.prototype in their blueprint. They are not directly in Dog, they’re in the ‘plans’ for Dog. So we aren’t creating new copies for each Dog, we’re simply sharing them, from the Dog.prototype, with all Dogs.

This article from Medium does a great job of explaining inheritance, and the significant impact it can have.

1 Like

I’m talking about the Dog constructor function.