Tell us what’s happening:
Your code so far
function Animal() {
}
Animal.prototype.eat = function() { console.log("nom nom nom"); };
// Animal.prototype.bark = function() { console.log("bark bark bark"); };
function Dog() { }
// Add your code below this line
Dog.prototype = {
constructor: Dog,
...Animal.prototype,
bark() {
console.log('Woof')
}
}
// Add your code above this line
let beagle = new Dog();
beagle.eat(); // Should print "nom nom nom"
beagle.bark(); // Should print "Woof!"
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance
Alright I completed the challenge but I didn’t like how I needed to add properties to the prototype individually three times as seen below
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
Dog.prototype.bark = () => {
console.log('Woof')
}
I thought changing it to a new object would make the job easier by taking advantage of the spread syntax like this
Dog.prototype = {
constructor: Dog,
...Animal.prototype,
bark() {
console.log('Woof')
}
}
However freecodecamp consoles an error which shows that it doesn’t recognize the spread syntax.
SyntaxError: unknown: Unexpected token (13:2)
11 | Dog.prototype = {
12 | constructor: Dog,
> 13 | ...Animal.prototype,
| ^
14 | bark() {
15 | console.log('Woof')
16 | }
But it works both my text editor, which is vscode, and browser devtools.
If this is just freecodecamp having a bug, and my solution is ‘correct’, is expanding the Animal prototype into a new Object bad practice or straight up wrong.