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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

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

本文标签: How to access Class properties outside of JavaScript ClassesStack Overflow