0

So I am working with the ES6 class stuff, which I've not had a chance to mess around with before, and event handlers, and I'm encountering an issue with the value of my this.

Javascript:

class Chat {
    constructor() {
        /*code*/
    }

    handleOnKeyDown() {
        console.log("A key was pressed somewhere on the page!")
        console.log(this)
    }
}

HTML:

let chat = new Chat()

chat.handleOnKeyDown() //this === [Chat Object]

document.onkeydown = chat.handleOnKeyDown //this === #document

How is my this being overwritten, and how can I prevent it from doing so? I don't particularly need the this from the event handler, since it's just literally the entire document, and isn't giving me any extra context.

  • `this` does not get "overwritten", it is an inherent property of the JavaScript language and is always exactly what it should be. It always points to the execution context of either of the code that's running, or in the case of arrow functions, of the code that declared the code that's now running. The result you're seeing is exactly what should happen: the ancient `on...` handler will run in a detached context, so if you don't force the correct context, `this` will be the thing whose `on...` is getting triggered. Also: don't use `on...`, use `addEventListener`, probably with an arrow function – Mike 'Pomax' Kamermans Feb 03 '20 at 23:36
  • Not really @jonrsharpe – jumpsplat120 Feb 03 '20 at 23:43

0 Answers0