0
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");

I don't even know how to ask this question, but here's my problem...

console.log(this.word)

This logs "undefined" to the console, because this refers to window instead of the TestClass. I want this.word to refer to "banana", and I would like to be able to use the e.charCode part at the same time.

How would I do that?

Ludde
  • 481
  • 1
  • 4
  • 3
  • Thank you for the link. I tried searching on my own but couldn't find a single relevant link anywhere. After all, I didn't know the technical terms to search for. – Ludde Oct 21 '18 at 15:01

2 Answers2

2

You need to either pass in the this of your class object:

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

Or you can use an arrow-function:

window.addEventListener("click", () => this.logWord())
Ram
  • 143,282
  • 16
  • 168
  • 197
Christian
  • 22,585
  • 9
  • 80
  • 106
0

Simply pass this to your event listeners.

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");
vrintle
  • 5,501
  • 2
  • 16
  • 46