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

问题描述 投票:0回答:2

我有两节课。我想从实例访问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?

我知道如何解决它并访问type,但......

// 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的情况下实现它?

javascript prototypal-inheritance
2个回答
1
投票

是的,如果你要将type添加到原型中:

  Animal.prototype.type = "animal";

或者你可以隐藏在Animal.apply糖背后的class电话:

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

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

1
投票

Rabbit.prototype = Object.create(Animal.prototype);只扩展了prototype链中定义的属性。构造函数中定义的属性不会被扩展。

试试这个,

...    
Rabbit.prototype = new Animal();
...

更新示例:

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

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

Rabbit.prototype = new Animal();
Rabbit.prototype.constructor = Rabbit;

const rabbit = new Rabbit('Bunny');
console.log(rabbit.name);
console.log(rabbit.type);
© www.soinside.com 2019 - 2024. All rights reserved.