.
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 ?
兔子是兔子的对象,而不是动物(直接)所以兔子的原型将指向兔子的原型,兔子的原型将指向动物的原型
检查一下
rabbits[1].__proto__ === Rabbit.prototype
这是因为rabbits[1]
是Rabbit
的一个例子 - 因此,它的原型指向Rabbit
,但由于Rabbit
是Animal
的延伸,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__);
当您创建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__)