JS inheritance lesson

Tell us what’s happening:
I don`t get it, why in this case beagle.eat() is undefined?

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 Animal();
console.log(beagle.eat());  // Should print "nom nom nom"

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 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

You have not not defined a Dog prototype to inherit from Animal’s prototype.

I know, but why my beagle can`t inherit directly from animal then??

It does using your code. That is why you see “nom nom nom” printed in the FCC Console.

Ehm, I still don`t get it, it prints both “nom nom nom” and undefined, so where is the truth. Why 2 times, isn`t suppose to be only one - “nom nom nom”? Because i don`t see the difference, is it inheriting from Dog or Animal in the case. Dog inherits all properties from Animal, so it`s like an Animal in that situation. So why i can`t walk through and inherit only from Animal for that eat() function, like an example. I commented the solution for the purpose.

You are first seeing “nom nom nom”, because the eat method has a console.log statement as follows:

console.log("nom nom nom");

The undefined comes from the console.log at the bottom which calls the eat method. Since the eat method does not return a value explicitly, the value undefined is returned, so that is what the main console.log displays.

If you change the last line to the following, you will only see “nom nom nom” displayed.

beagle.eat()

If you modify the eat method to the following, you would see your forum username on the line after “nom nom nom”.

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

But we didn`t call the eat method, so why it executed?Or i don`t know something from basics? -_-

OMG, my bad, now i understand -_-

You your question is answered to your satisfaction?

Yeah, many thanks, now i understood my mistakes :slightly_smiling_face: