簡體   English   中英

匿名函數和可變范圍

[英]Anonymous Functions and Variable Scope

我在這里閱讀有關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);
        };
}())

我的猜測是它與放在括號內的函數有關,但是如何? 這樣的編碼風格可以完成什么工作以及其他效果? 這是我應該更經常使用的東西嗎?如果是,什么時候?

這里的lastTime變量是通過Closure捕獲的。 這意味着它在定義的功能范圍之外仍然有效。

每當匿名函數主體引用其自身作用域之外的變量時,都會創建一個閉包。 閉包在JavaScript中非常有用,因為閉包允許您維護狀態而不會全局暴露狀態。

舉一個簡單的例子

function foo() {
    var count = 0;

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

通過在此處關閉count變量,我可以在setInterval使用它,而不必像其他情況那樣將count暴露給全局范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM