Tell us what’s happening:
How is animal being determined to be the super class? im familiar with java when you want to use inheritance its
Public Class Dog extends Animal
But what makes animal the parent or super? is it because of the
function Animal() {}
Your code so far
function Cat(name) {
this.name = name;
}
Cat.prototype = {
constructor: Cat,
};
function Bear(name) {
this.name = name;
}
Bear.prototype = {
constructor: Bear,
};
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("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/68.0.3440.106 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
It works how you would expect it to work. Prototypal inheritance may not work the same as Java’s classical inheritance, but it’s still logical - you need to set the prototype of the subtypes to the superclass. That isn’t explained in this challenge, so I can see where the confusion is coming from . Simply adding the eat property will just leave you with an Animal class that has an eat property, it isn’t connected to any of the individual animal classes.
If you set the prototype property to the parent class, you get the inheritance, which I think is explained in the next few lessons. ES6 syntax makes it a bit clearer (still doesn’t work any differently, but looks a lot more like Java):
class Animal {
constructor (name) {
this.name = name;
}
eats() {
return "nom nom nom";
}
}
class Bear extends Animal {
constructor (name) {
super(name);
}
}
Im still a little fuzzy on prototypes just from the first time it is brought up. I dont think I ever touched prototypes in my javascript class.
Just so im clear, and my own understanding if I use something like
function Animal() {}
Animal.prototype = {
numLegs: 4;
Any instance of animal has that numLegs property, so if I needed to I could call?
let dog = new Animal();
dog.numLegs
For inheritance then it would be
function Animal() {]
Animal.prototype = {
numLegs:4;
eat: function() {
console.log("nom nom nom");
}
}
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
let beagle = new Dog();
beagle.eat();