0

我在这里阅读了一篇关于 requestAnimationFrame 的文章,我意识到我在跟踪变量的范围和持久性时遇到了问题。稍作修改的代码如下:

(function() {

    //Note: lastTime is defined up here.
    var lastTime = 0;

    var vendors = ['ms', 'moz', 'webkit', 'o'];

    //Okay, so they're trying to set window.rAF to the appropriate thing based on browser
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
          'CancelRequestAnimationFrame'];
    }

    //...and if that doesn't work, turn it into a setTimeout
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {

            //I guess this is a way to make sure that the wait time
            //between renders is consistent

            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);

            lastTime = currTime + timeToCall;

            //Wait. They just assigned lastTime a value.
            //Why is this going to persist between calls to window.rAF?
            //The variable lastTime was defined inside this function, not in the window.

            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}())

我的猜测是它与放在括号内的函数有关,但是如何?使用这种编码风格可以完成什么以及我可以期待什么其他效果?这是我应该开始更经常使用的东西吗?如果是,什么时候?

4

1 回答 1

3

这里的变量lastTime是通过闭包捕获的。这意味着它在其定义的函数范围之外保持活动状态。

每当匿名函数体引用其自身范围之外的变量时,都会创建闭包。闭包在 JavaScript 中非常有用,因为它们允许您在不全局公开状态的情况下维护状态。

举一个简化的例子,

function foo() {
    var count = 0;

    setInterval(function bar() {
        console.log(count++);
    }, 100);
}

通过在count此处关闭变量,我可以在setInterval不暴露count于全局范围的情况下使用它,否则我必须这样做。

于 2013-09-20T18:39:44.360 回答