我知道这类问题有很多解决方案,但不知怎的,它们非常复杂。
我想知道一旦调用函数会发生什么。例如,在我的示例代码中,当我调用keyboardHandler()
一次时,eventHandler会将keyPressed()
和keyReleased()
函数添加到keydown
和keyup
事件中。但由于它们不是全局函数(但在另一个函数中定义),当按下某个键时,我是否能够在全局区域外访问它们?
如果是,这是否意味着一旦被调用的函数有点存储在内存中?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var leftPressed = false;
var upPressed = false;
var rightPressed = false;
var downPressed = false;
function keyboardHandler() {
document.addEventListener("keydown", keyPressed);
document.addEventListener("keyup", keyReleased);
function keyPressed(e) {
switch(e.keyCode) {
case 37:
leftPressed = true;
break;
case 38:
upPressed = true;
break;
case 39:
rightPressed = true;
break;
case 40:
downPressed = true;
break;
}
}
function keyReleased(e) {
switch(e.keyCode) {
case 37:
leftPressed = false;
break;
case 38:
upPressed = false;
break;
case 39:
rightPressed = false;
break;
case 40:
downPressed = false;
break;
}
}
}