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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With