Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 477
Steez Avatar asked Oct 18 '25 22:10

Steez


1 Answers

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();
like image 199
Mike Cluck Avatar answered Oct 20 '25 13:10

Mike Cluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!