Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1
class KeyCodeClass1 {
constructor() {
this.space;
}
KeyDown(e) {
if (e.keyCode == 32) { this.space = true }
}
KeyUp(e) {
if (e.keyCode == 32) { this.space = false }
}
}
var KeyCode1 = new KeyCodeClass1();
window.addEventListener("keydown", KeyCode1.KeyDown, false);
window.addEventListener("keyup", KeyCode1.KeyUp, false);
setInterval(loop1,10);
function loop1() {
console.log(KeyCode1.space);
}
Currently, my console is showing undefined. Even when I press the spacebar, which has a keycode of 32
, the value remains undefined. To try and resolve this, I created a function to return the value:
Attempt 2
class KeyCodeClass2 {
constructor() {
this.space;
}
KeyDown(e) {
if (e.keyCode == 32) { this.space = true }
}
KeyUp(e) {
if (e.keyCode == 32) { this.space = false }
}
Space() {
return this.space;
}
}
var KeyCode2 = new KeyCodeClass2();
window.addEventListener("keydown", KeyCode2.KeyDown, false);
window.addEventListener("keyup", KeyCode2.KeyUp, false);
setInterval(loop2,10);
function loop2() {
console.log(KeyCode2.Space());
}
Still getting undefined in the console. In the third attempt, I initialized this.space
in the constructor with either true
or false
:
Attempt 3
constructor() {
this.space = false;
}
Now, the console displays false
. However, pressing the spacebar does not change it to true
.
It got me thinking about whether the functions within the class are functioning properly. Here's an example to demonstrate that they are indeed working: Attempt 4
class KeyCodeClass4 {
constructor() {
this.space = false;
}
KeyDown(e) {
if (e.keyCode == 32) {
KeyCodeClass.space = true;
console.log("space Down");
}
}
KeyUp(e) {
if (e.keyCode == 32) {
KeyCodeClass.space = false;
console.log("space Up");
}
}
}
var KeyCode4 = new KeyCodeClass4();
window.addEventListener("keydown", KeyCode4.KeyDown, false);
window.addEventListener("keyup", KeyCode4.KeyUp, false);
I am troubleshooting like this to enhance the readability and comprehension of my code. Any assistance you can provide on this matter would be greatly appreciated.