Object.prototype没有进行正确的继承

时间:2018-01-04 19:15:22

标签: javascript constructor prototype

我有一个基于类继承的代码。 Rabbit构造函数动物原型继承方法,然后使用动物方法创建对象 兔子强>

我无法理解 - 为什么Rabbit构造函数不希望继承Animal.prototype.name方法。它与Animal.prototype.run完全相同,但它不起作用......

    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

2 个答案:

答案 0 :(得分:2)

你有对象字段" name"和功能"名称"。 Field正在覆盖该功能。

解决方案相当简单 - 重命名一个或另一个。

答案 1 :(得分:2)

.name不是方法,在构造函数中为它赋予参数字符串。这个属性会影响继承的方法。调用字符串将产生错误。

将其更改为

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"