I am currently working on a code that involves class inheritance. The Rabbit constructor is supposed to inherit methods from the Animal prototype in order to create an object named rabbit with Animal methods.
However, I am struggling to understand why the Rabbit constructor is not inheriting the Animal.prototype.name method. It is similar to the Animal.prototype.run method, but for some reason it is not functioning as expected...
function Animal(name) {
this.name = name;
this.speed = 0;
}
Animal.prototype.run = function(speed) {
this.speed += speed;
console.log( this.name + ' run, speed ' + this.speed );
};
Animal.prototype.name = function(name) {
this.name = name;
console.log( 'Rabbit name ' + this.name );
};
Animal.prototype.stop = function() {
this.speed = 0;
console.log( this.name + ' stay' );
};
function Rabbit(name) {
Animal.apply(this, arguments);
}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
Rabbit.prototype.jump = function() {
this.speed++;
console.log( this.name + ' jump' );
};
var rabbit = new Rabbit('Rabbit');
rabbit.name(); // Error, but it must display "Rabbit"
rabbit.run(); // works fine
rabbit.jump(); // works fine