Suppose the following class:
class MyClass {
private keysPressed: string[] = [];
configure() {
window.addEventListener('keyup', this.handleKeyUp);
}
handleKeyUp(e: KeyboardEvent) {
this.keysPressed.push(e.key);
}
}
The following throws an error:
const instance = new MyClass();
instance.configure(); // TypeError: Cannot read properties of undefined (reading 'push')
If I add console.log(this.keysPressed)
in configure
, it sees keysPressed
as expected, however handleKeyUp
seems to behave differently.
Why is this happening?