关于继承我不了解的一些事情

问题描述 投票:4回答:3

I have created such a table on "inheritance".

  1. 比较---原型---> Animal.prototype(构造函数,运行)
  2. 兔子--- [[原型]] --->比较
  3. 兔子---原型--->动物
  4. Rabbit.prototype --- [[prototype]] ---> Animal.prototype(构造函数,运行)
  5. 兔子(名字:'白兔')--- [[原型]] ---> Rabbit.prototype
  6. 兔子(名字:'白兔')---原型--->兔子

.

  • 认为他们是真的。但请说明是否有错误。我写了一些代码来理解“继承”的主题。但有些人没有给出我想要的结果。但有些人没有给出我想要的结果。 (注释行中的规范)
  class Animal {
    constructor(name, speed) {
      this.speed = speed;
      this.name = name;
    }

    run(speed = 0) {
      this.speed += speed;
      console.log(`${this.name} runs with speed ${this.speed}.`);
    }

    static compare(animalA, animalB) {
      console.log(animalA.speed - animalB.speed);
    }
  }

  class Rabbit extends Animal {
    hide() {
      console.log(`${this.name} hides!`);
    }
  }

  let rabbits = [
    new Rabbit("White Rabbit", 5),
    new Rabbit("Black Rabbit", 10)
  ];

  console.log(Rabbit.__proto__ === Animal); // true (not problem)

  console.log(Animal.__proto__ === Function.prototype); // true (not problem)

  console.log(Rabbit.__proto__ === Animal.prototype); //(not problem)
  console.log(Rabbit.__proto__.prototype === Animal.prototype); //(not problem)

  console.log(rabbits[1].__proto__ === Animal.prototype); 
  // this problem
  // rabbit(name:'White Rabbit') ---[[prototype]]---> Rabbit.prototype ?
javascript arrays class object ecmascript-6
3个回答
1
投票

兔子是兔子的对象,而不是动物(直接)所以兔子的原型将指向兔子的原型,兔子的原型将指向动物的原型

检查一下

rabbits[1].__proto__ === Rabbit.prototype

1
投票

这是因为rabbits[1]Rabbit的一个例子 - 因此,它的原型指向Rabbit,但由于RabbitAnimal的延伸,Rabbit.prototype指向Animal.prototype

class Animal {
  constructor(name, speed) {
    this.speed = speed;
    this.name = name;
  }

  run(speed = 0) {
    this.speed += speed;
    console.log(`${this.name} runs with speed ${this.speed}.`);
  }

  static compare(animalA, animalB) {
    console.log(animalA.speed - animalB.speed);
  }
}

class Rabbit extends Animal {
  hide() {
    console.log(`${this.name} hides!`);
  }
}

let rabbits = [
  new Rabbit("White Rabbit", 5),
  new Rabbit("Black Rabbit", 10)
];

console.log(rabbits[1].constructor.name);
console.log(Rabbit.__proto__);

1
投票

当您创建Rabbit类的对象[rabbit]时,它将Rabbit.prototype作为其[[Prototype]]属性。和rabbit.proto([[Prototype]])获取Animamal.prototype属性。所以这就是兔子继承其祖先属性的方式。

rabbit[1]<--(Inherits from Rabbbit which is rabbit[1].__proto__) <-- (Inherits from Animal rabbit[1].__proto__.__proto__)
© www.soinside.com 2019 - 2024. All rights reserved.