admin管理员组文章数量:1325647
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!!
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!!
Share Improve this question asked Apr 5, 2017 at 20:32 SteezSteez 2296 silver badges17 bronze badges3 Answers
Reset to default 7It'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);
本文标签: How to access Class properties outside of JavaScript ClassesStack Overflow
版权声明:本文标题:How to access Class properties outside of JavaScript Classes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742158580a2424514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论