。
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 ?
答案 0 :(得分:2)
兔子是兔子的对象,而不是动物的对象(直接) 因此,兔子的 proto 将指向Rabbit的proto,而Rabbit的proto将指向Animal的proto
检查此
rabbits[1].__proto__ === Rabbit.prototype
答案 1 :(得分:1)
这是因为rabbits[1]
是Rabbit
的实例-因此,其原型指向Rabbit
,但是由于Rabbit
是Animal
的扩展,所以{ {1}}指向Rabbit.prototype
:
Animal.prototype
答案 2 :(得分:0)
当您创建Rabbit类的对象[rabbit]时,它将获得Rabbit.prototype作为其[[Prototype]]属性。 proto (即[[Prototype]])获得Animamal.prototype属性。因此,这就是兔子继承其祖先属性的方式。
rabbit[1]<--(Inherits from Rabbbit which is rabbit[1].__proto__) <-- (Inherits from Animal rabbit[1].__proto__.__proto__)