无法访问Javascript对象内的类变量

时间:2019-11-26 08:00:26

标签: javascript html function oop variables

我的对象有一个事件监听器,需要在用户输入时更新类变量 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>

0 个答案:

没有答案