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
部分。
我该怎么做?
答案 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");