简体   繁体   English

Javascript游戏循环状态在匿名函数中

[英]Javascript game loop state in an anonymous function

I'm messing around with canvas, and starting by reading a bunch of game loop snippets/posts and combining them into the best one possible. 我正在搞乱画布,首先阅读一堆游戏循环片段/帖子并将它们组合成最好的一个。

I came upon this snippet today (it's part way through a post , so they make further iterations on it later. But I'm integrating the ideas as I go), but it's perplexing me a little. 今天我发现了这个片段(这是一篇文章的部分内容,所以他们稍后会对它进行进一步的迭代。但是我正在整合这些想法),但这让我感到困惑。

Game.run = (
    function() {
        var loops = 0;
        var skipTicks = 1000 / Game.fps;
        var maxFrameSkip = 10;
        var nextGameTick = (new Date).getTime();

        return function {
            loops = 0;

            while ((new Date).getTime() > nextGameTick && loops < maxFrameSkip) {
                Game.update();
                nextGameTick += skipTicks;
                loops++;
            }

            Game.draw();
        };
    }
)();

Game._intervalId = setInterval(Game.run, 1000 / Game.fps);

So Game.run gets assigned the result of the outer function, which is the inside function. 所以Game.run被赋予外部函数的结果,这是内部函数。 But the inside function relies on nextGameTick , which is defined in the outer function... 但是内部函数依赖于nextGameTick ,它在外部函数中定义...

So will this game be keeping its state in the outer anonymous function? 那么这个游戏会在外部匿名功能中保持其状态吗? If so, any ideas why they did that? 如果是这样,任何想法为什么他们这样做?

And as for eg loops , which is set to 0 every call, is it declared outside to avoid re-declaring the variable again each time? 至于eg loops ,每次调用都设置为0,它是否在外面声明,以避免每次重新声明变量?

This type of construction is called an immediately invoked function expression or IIFE . 这种类型的构造称为立即调用的函数表达式IIFE

This pattern is used to manage scope. 此模式用于管理范围。 In this case, we are preventing variables like loops and skipTicks from leaking into the global scope. 在这种情况下,我们阻止loopsskipTicks等变量泄漏到全局范围。 More importantly, they are caught in the closure of the inner function, and thus persist across calls to that inner function. 更重要的是,它们在内部函数的闭包中被捕获,因此在对内部函数的调用中持续存在。 By using an IIFE, only our inner function can see this state, and it is hidden from the global context. 通过使用IIFE,只有我们的内部函数可以看到这种状态,并且它在全局上下文中是隐藏的。

Here's a decent article on the pattern. 这是关于模式的一篇不错的文章 See in particular the section on saving state with closures. 请特别参阅有关使用闭包保存状态的部分。

Yes it will. 是的,它会的。

The local frame of the function you returned is inside the local frame of the Game.run function. local frame你返回的功能是内部local frame的Game.run功能。 Therefore, any variable that gets changed in Game.run around the function you return is persistent. 因此,围绕您返回的函数在Game.run中更改的任何变量都是持久的。 The parent frame of that function will look inside of Game.run any time you try to reference your nextTick variable. 只要您尝试引用nextTick变量,该函数的父框架就会在Game.run中查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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