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

时间:2019-04-18 16:03:14

标签: javascript prototypal-inheritance

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

2 个答案:

答案 0 :(得分:1)

是的,如果您要在原型中添加type

  Animal.prototype.type = "animal";

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

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

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

答案 1 :(得分: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);