简体   繁体   English

如何在JavaScript类之外访问类属性

[英]How to access Class properties outside of JavaScript Classes

How is the sound property not properly private in this JavaScript class? 声音属性如何在此JavaScript类中不适当地私有? 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. 我在视频中看到了这一点,并试图访问课堂外的sound属性,但不能。

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

You need to create an instance of the class using new . 您需要使用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类分配一个默认属性,而不必创建它的新实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM