【问题标题】:How to access Class properties outside of JavaScript Classes如何访问 JavaScript 类之外的类属性
【发布时间】:2017-04-05 20:32:06
【问题描述】:
这个 JavaScript 类中的 sound 属性如何不正确地私有?此外,如何在课堂外访问它?我在视频中看到了这一点,并试图在课堂外访问 sound 属性,但无法访问。
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
谢谢!!
【问题讨论】:
标签:
javascript
class
ecmascript-6
【解决方案1】:
它不是私有的,因为您可以在创建类的实例后从外部访问它。
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();
【解决方案2】:
您需要使用new 创建该类的实例。当你没有类的实例时,构造函数还没有被执行,所以还没有 sound 属性。
var foo = new Dog();
console.log(foo.sound);
或
这将为 Dog 类分配一个默认属性,而无需创建它的新实例。
Dog.__proto__.sound = 'woof';
console.log(Dog.sound);
【解决方案3】:
你需要创建你的类的实例。
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
console.log(new Dog().sound);