簡體   English   中英

如何通過構造函數的實例訪問構造函數的屬性?

[英]How can I access a property of a constructor through an instance of that constructor?

這里的構造函數是 Animal。 它有兩個實例duck 和beagle。 有一個名為eat() 的function 實際上是Animal 的原型。

function Animal() {
  this.color = "brown";
 }

Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};

let duck = Object.create(Animal.prototype); 
let beagle = Object.create(Animal.prototype); 
duck.eat();
console.log(duck.color);

這里

duck.eat() 

有效,但鴨子也必須繼承棕色,對嗎? 為什么我無法使用它訪問它

duck.color ?

Animal.prototype上沒有color屬性。 當構造函數 function 被調用時,它被動態添加到 object 中……但你根本沒有調用構造函數 function。

如果要創建 class 的實例,則調用構造函數 function。 不要使用Object.create

 function Animal() { this.color = "brown"; } Animal.prototype = { eat: function() { console.log("nom nom nom"); } }; let duck = new Animal(); let beagle = new Animal(); duck.eat(); console.log(duck.color);

不,它不會繼承,

請閱讀Object.create的定義。

“Object.create() 方法創建一個新的 object,使用現有的 object 作為新創建對象的原型”

意味着,只有prototype will be copied from existing object on will be placed in newly create object's prototype

這里color是實例變量而不是原型。 因此在新創建的duck object 中將不可用。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

暫無
暫無

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

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