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

时间:2017-04-05 20:32:06

标签: javascript class ecmascript-6

这个JavaScript类中的声音属性如何不正确隐私?另外,如何在课外访问它?我在一个视频中看到了这个并试图访问课堂外的声音属性而不能。

<script type="text/javascript">
$(document).ready(function () {
    getMessage();
});

function getMessage()
{
    $.get("load_messages.php?id=<?php echo $ConversationID?>", function (result) {
        $('#refresh').html(result);
        setTimeout(getMessage,3000);
    });
}
</script>

谢谢!

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

您需要使用new创建该类的实例。如果您没有该类的实例,则构造函数尚未执行,因此尚无声音属性。

var foo = new Dog();
console.log(foo.sound);

这将为Dog类分配一个默认属性,而不必创建它的新实例。

Dog.__proto__.sound = 'woof';
console.log(Dog.sound);

答案 2 :(得分:0)

您需要创建班级的实例。

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}

console.log(new Dog().sound);

相关问题