0

I know there are many solutions with this type of question but somehow they are very complex.

I wanted to know what happens once a function is called. For example, in my sample code, when I call keyboardHandler() once, the eventHandler will add the keyPressed() and keyReleased() functions to the keydown and keyup events. But since they are not global functions (but defined inside another function), will I be able to access them outside, in the global area, when a key is pressed?

If yes, does that mean a function once called is somewhat stored in the memory?

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;  
        }
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dhruv Chadha
  • 1,161
  • 2
  • 11
  • 33
  • 1
    This is called a closure. its scope will be the function in which it is defined. So no, it isn't global... and actually gets rebuilt (or at least re-pulled) every time time parent function gets called. Since JavaScript runs so quickly, this is generally not a problem. As far as it being in memory... yes, it will stay in memory until it gets garbage collected, but I don't think its memory residence is germane to anything. – John Green Jun 28 '16 at 05:29
  • So suppose I actually want to run this statement in global, `setInterval(function() {console.log(leftPressed)},1000);` and I know leftPressed will never be = true. So what do i do ? @JohnGreen – Dhruv Chadha Jun 28 '16 at 05:46
  • leftPressed is in the global context. Because of that, if it gets modified, that modification is in the global context. So, leftPressed *will* be true on keydown of keyCode 37.... of course, it will be released back up when you keyup... – John Green Jun 28 '16 at 05:56
  • Read this: http://stackoverflow.com/questions/14933290/is-a-function-stored-in-memory-only-once – barbq Jun 28 '16 at 06:00

0 Answers0