Hi I don't get the variable out of the KeyCodeClass. Here is what I tryed: TEST 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);
}
Now I get in my console undefined. So if I press my spacebar what equals e.keyCode == 32
the undefined stay's printed. So what if we return the value in a fuction we get this: TEST 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());
}
So still an undefined in the console. the 3 test where I did defined the this.space
with a true
or false
in the constructor: TEST 3
constructor() {
this.space = false;
}
Well we get the false
in the console. But when I press the spacebar is goes not to true
.
So I began to wonder whether the functions in the class are working. Here it is proved that they work fine: TEST 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);
why am I doing this? it is to make my code more readable and understandable. Please help me with this problem.