[英]How to access Class properties outside of JavaScript Classes
聲音屬性如何在此JavaScript類中不適當地私有? 此外,如何在課堂之外訪問它? 我在視頻中看到了這一點,並試圖訪問課堂外的sound屬性,但不能。
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
謝謝!!
它不是私有的,因為您可以在創建類的實例后從外部訪問它。
class Dog { constructor() { this.sound = 'woof'; } talk() { console.log(this.sound); } } let dog = new Dog(); console.log(dog.sound); // <-- // To further drive the point home, check out // what happens when we change it dog.sound = 'Meow?'; dog.talk();
您需要使用new
創建類的實例。 當您沒有該類的實例時,構造函數尚未執行,因此尚無聲音屬性。
var foo = new Dog();
console.log(foo.sound);
要么
這將為Dog類分配一個默認屬性,而不必創建它的新實例。
Dog.__proto__.sound = 'woof';
console.log(Dog.sound);
您需要創建類的實例。
class Dog { constructor() { this.sound = 'woof'; } talk() { console.log(this.sound); } } console.log(new Dog().sound);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.