如何在JavaScript类之外访问类属性

Ste*_*eez 2 javascript class ecmascript-6

声音属性如何在此JavaScript类中不适当地私有?此外,如何在课堂之外访问它?我在视频中看到了这一点,并试图访问课堂外的sound属性,但不能。

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!!

Mik*_*uck 5

它不是私有的,因为您可以在创建类的实例后从外部访问它。

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();
Run Code Online (Sandbox Code Playgroud)