Reputation: 229
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!!
Upvotes: 4
Views: 4135
Reputation: 3975
You need to create instance of your class.
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
console.log(new Dog().sound);
Upvotes: 0
Reputation: 32511
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();
Upvotes: 7
Reputation: 176
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);
Upvotes: 0