Add Methods After Inheritance prototype property

Tell us what’s happening:
this may be because I didn’t pay attention where I should have, but I don’t understand why the
code:

Dog.bark = function() {
    console.log("Woof!");
}

doesn’t work and instead you need Dog.prototype.bark = function() {…}

Your code so far


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

function Dog() { }

// Add your code below this line

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function() {
    console.log("Woof!");
}

// Add your code above this line

let beagle = new Dog();
beagle.constructor = Dog;

beagle.eat(); // Should print "nom nom nom"
beagle.bark(); // Should print "Woof!"

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) 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/add-methods-after-inheritance/

Because.

Because Mama JavaScript says so.

But seriously, I’m going to be half pulling this out of my butt so anyone is free to correct me if I’m wrong, but here is how I think of it…

Because Dog is the constructor function. It doesn’t have a property bark, the prototype does. For example:

// ...
Dog.prototype.bark = function() {
    console.log("Woof!");
}

console.log(Dog);
// ƒ Dog() {}
console.log(Dog.bark);
// undefined
console.log(Dog.prototype);
// Animal {bark: ƒ}
console.log(Dog.prototype.bark);
// ƒ () { console.log("Woof!") }

Yes, it’s a bit odd. And if the creators of JS had decided to allow you to write it that way, perhaps they could have. It’s been a while since I did this in another language so I can’t remember how it’s handled there. I will say that the way JS handles OOP is a little odd, but that’s the way it is. Don’t confuse the constructor function with the prototype that it is using.