Set the Child's Prototype to an Instance of the Parent Need help!

Tell us what’s happening:
I have a question about this part, I thought if we use the ‘new’ keyword to create a new object, that new object only contains attributes with the ‘this’ keyword. So why in this case, can ‘beagle’ inherit all the attributes of ‘Dog’?

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; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/78.0.136 Chrome/72.0.3626.136 Safari/537.36.

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

everything is describe in left panel still want to know more read javascript documentation
link:-https://devdocs.io/javascript/

1 Like

When you use new keyword, you are creating an instance/object from either a function constructor or a class constructor. In this case, it’s a function constructor. Then you get access to all the variables that are declared with this inside the function constructor. In this case Dog constructor inherits from Animal constructor and beagle is an instantiation of Dog constructor so beagle has access to all the methods and this values of Animal constructor.

1 Like