簡體   English   中英

為什么在JS繼承中無法從子類實例訪問父類的屬性?

[英]Why I can't access a property of parent class from child class instance in JS inheritance?

我有兩節課。 我想從實例訪問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來實現?

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

  Animal.prototype.type = "animal";

或者你可以隱藏Animal.apply背后的通話class糖:

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

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

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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM