我的对象有一个事件监听器,需要在用户输入时更新类变量 hat 的值,但是看来在函数 UpdateHat 。我认为它与范围有关,但是我认为作为类变量,应该可以在类中的任何地方访问它。对于此问题的任何帮助,将不胜感激。
<script>
class Clothes {
constructor() {
this.hat = 'top hat';
}
UpdateHat() {
console.log(this.hat); // will print 'Undefined'
this.hat = this.value;
console.log(this.hat); // will print input value
}
UpdateVariables() {
document.getElementById("hat").addEventListener('input', this.UpdateHat);
}
}
var clothes = new Clothes();
clothes.UpdateVariables();
</script>