gpt4 book ai didi

javascript - 为什么我无法在JS继承中从子类实例访问父类的属性?

转载 作者:行者123 更新时间:2023-12-01 01:04:45 26 4
gpt4 key购买 nike

我有两个类。我想从实例访问 Parent 的 type 属性:

// Parent class
function Animal() { this.type = 'animal' }

// Child class
function Rabbit(name) { this.name = name }

// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too

// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?

我知道如何解决它并访问类型,但是...

// all is the same

// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}

// all is the same

rabbit.name // => Bunny
rabbit.type // => animal

...但是为什么它在第一个示例中不起作用?不使用Animal.apply是否可以实现它?

最佳答案

是的,如果您将type添加到原型(prototype)中:

  Animal.prototype.type = "animal";

或者您可以将 Animal.apply 调用隐藏在 class 糖后面:

 class Animal {
constructor() {
this.type = "animal";
}
}

class Rabbit {
constructor(name) {
super(); // <<<
this.name = name;
}
}

关于javascript - 为什么我无法在JS继承中从子类实例访问父类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com