如何在JavaScript类之外访问类属性 [英] How to access Class properties outside of JavaScript Classes

查看:84
本文介绍了如何在JavaScript类之外访问类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此JavaScript类中,声音属性如何不正确私有?此外,如何在课堂之外访问它?我在视频中看到了这一点,并试图访问课堂外的sound属性,但是不能.

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

谢谢!

推荐答案

它不是私有的,因为您可以在创建类的实例后从外部访问它.

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

这篇关于如何在JavaScript类之外访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆