Search code examples
javascriptconstructorprototype

Object.prototype does not make right inheriting


I have a code that based on class inheritance. The Rabbit constructor inherit methods from Animal prototype and then create an object rabbit with Animal methods.

I can not understand - why the Rabbit constructor does not want inherit the Animal.prototype.name method. It's exactly as an Animal.prototype.run, but it does not work...

    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


Solution

  • .name is not a method, in the constructor it gets assigned the argument string. This own property shadows the inherited method. Calling the string will produce the error.

    Change it to

    Animal.prototype.setName = function(name) {
      this.name = name;
      console.log( 'Rabbit name ' + this.name );
    };
    
    …
    
    console.log(rabbit.name); // displays "Rabbit"
    rabbit.setName("Roger"); // displays "Rabbit name Roger"