[英]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.