简体   繁体   中英

How to define local variable once using HTML canvas with javascript while using a setInterval loop?

I am programming a simple game using the HTML canvas and editing it with JavaScript. I several functions which draw something on the canvas, and all those functions are looping using a single setInterval. However some of these functions need to have a local variable that contains a certain attribute about that function (to be precise, a toggle, whether a function is "xx" or not), and as there will be many of these functions, storing this variable in the global window is very unpractical.

Is there a way of defining the variable (or attribute) in this function without this variable being reset every loop?

So in code I have:

var DoSomething = function(){
var xx = new Boolean
[...]
if (condition) { xx = false}
if (condition) { xx = true}
}

And all is executed in the main loop:

var gameLoop = function(){
DoSomething()
OtherFunctions()
}

var startGame = function(){
setInterval(gameLoop,10)
}

startGame()

Like I said, defining xx in the global window would be very unpractical as there are many function with this xx attribute/variable. But right now, the loop keeps resetting xx at the start of the loop. Is there a way of defining the local variable here, without it being reset with every loop of the setInterval?

By wrapping your code inside a function, everything inside that function becomes hidden from the rest of the world. So now you can declare variables outside your functions, and they will remain private and only accessible by your program.

(function() {
    var xx = new Boolean,
        loop;

    var DoSomething = function() {
      // xx will now keep it's state
        if (condition) { xx = false; }
    }

    var gameLoop = function() {
        DoSomething();
        OtherFunctions();
    }

    var startGame = function() {
        loop = setInterval(gameLoop, 10);
    }
}());

The extra parenthesis at the end makes the function call itself immediately, so as soon as the script is loaded the function will run

e.g function() {<code>}()

I recommend reading about prototypical inheritance and using it to create classes to represent objects in your game. It's a good way to get started with OOP in javascript.

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

Also read up on closures to better understand how the above example works. How do JavaScript closures work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM