如何在同一个类中创建的事件侦听器中引用一个类?

时间:2018-10-21 14:45:27

标签: javascript dom

class TestClass {
    constructor(word) {
        this.word = word;
        window.addEventListener("keypress", this.logCharCodeAndWord);
        window.addEventListener("click", this.logWord)
    }
    logCharCodeAndWord(e) {
        console.log(e.charCode);
        console.log(this.word)
    }
    logWord() {
        console.log(this.word)
    }
}

var testObject = new TestClass("banana");

我什至不知道怎么问这个问题,但这是我的问题...

console.log(this.word)

这会将“未定义”记录到控制台,因为this是指window而不是TestClass。我希望this.word引用“香蕉”,我希望能够同时使用e.charCode部分。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您需要传入类对象的this

window.addEventListener("click", this.logWord.bind(this))

或者您可以使用箭头功能:

window.addEventListener("click", () => this.logWord())

答案 1 :(得分:0)

只需将this传递给事件监听器即可。

window.addEventListener("keypress", e => this.logCharCodeAndWord(e, this));
window.addEventListener("click", () => this.logWord(this));

class TestClass {
    constructor(word) {
        this.word = word;
        window.addEventListener("keypress", e => this.logCharCodeAndWord(e, this));
        window.addEventListener("click", () => this.logWord(this));
    }
    logCharCodeAndWord(e, self) {
        console.log(e.charCode);
        console.log(self.word)
    }
    logWord(self) {
        console.log(self.word)
    }
}

var testObject = new TestClass("banana");