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