0

I'm trying to simulate the "class" syntax in JavaScript. How do I call the function from an object's prototype when redefining it? In the example, I'm trying to extend the Bear object's sound function.

function Animal(name) {
    this.name = name;
}
Animal.prototype.sound = function() { console.log("I'm " + this.name); }

function Bear(name) {
    Animal.call(this, name)
}
Bear.prototype = new Animal();
Bear.prototype.sound = function() { this.prototype.sound(); console.log("growl!"); }

const cal = new Bear("Callisto")
cal.sound() // Should be: I'm Callisto growl!
console.log(cal)
Ondrej Sotolar
  • 1,352
  • 1
  • 19
  • 29

1 Answers1

1

You could directly access the method on the Animals prototype:

Bear.prototype.sound = function() { 
 Animal.prototype.sound.call(this); 
 console.log("growl!"); 
};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151