简体   繁体   中英

How to access Class properties outside of JavaScript Classes

How is the sound property not properly private in this JavaScript class? Additionally, how can it be accessed outside the class? I saw this in a video and attempted to access the sound property outside the class and could not.

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}

Thanks!!

It's not private because you can access it from the outside after creating an instance of the class.

 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(); 

You need to create an instance of the class using new . When you don't have an instance of the class, the constructor has yet to be executed, so there's no sound property yet.

var foo = new Dog();
console.log(foo.sound);

or

This will assign a default property to the Dog class without having to create a new instance of it.

Dog.__proto__.sound = 'woof';
console.log(Dog.sound);

You need to create instance of your class.

 class Dog { constructor() { this.sound = 'woof'; } talk() { console.log(this.sound); } } console.log(new Dog().sound); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM