Use Inheritance So You Don't Repeat Yourself - Explanation how it works?

I’m confused on how this works. I define two constructor functions and their prototypes.

function Cat(name) {
  this.name = name; 
}
Cat.prototype = {
  constructor: Cat, 
};



function Bear(name) {
  this.name = name; 
}

Bear.prototype = {
  constructor: Bear, 
};

Okay, then i define another prototype and run it like a function?

function Animal() { }

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

Then somehow both bear and cat suddenly have this prototype property apart of them? What if i had another constructor and prototype for Dog() and did not want it to inherit it? Does it run off of scope?

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself

4 Likes

If you continue on with the assignments i believe this will be explained, i.e. how to use the supertype (or parent). But no, bear and cat are not yet “connected” to the Animal.

3 Likes

Yeah, the prompt is actually misleading. This is really a set up to inheritance, but not really create any inheritance.

What you really did is created a Supertype that both Bear and cat can inherit common methods from, but you have not actually made Bear and Cat subtype of animal, yet.

This is one of those thing that because of how FCC breaks up the lesson, you wouldn’t have the full picture until you complete basically the thread of tutorials

4 Likes

@lasjorg

Thanks both for your help, just did that challenge and it is fully explained it.

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

1 Like