3

there are a lot of places (e.g. How to use requestAnimationFrame?) that fix window.requestAnimationFrame as below. I do not understand why the right hand side of the assignment is wrapped in to a function call.

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

4

3 回答 3

0

I've wondered the same thing before. I'm pretty sure Google just really likes closures. Granted there is not one variable in there, it's a 'safe' thing to do.

As far as I can tell, this is the exact same thing, without any change of interfering with namespaces (a general reason to use a closure like that):

window.requestAnimFrame = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
于 2012-04-19T22:06:13.230 回答
0

In the OP example, putting the code into the closure does nothing (at least what I am aware of :-)

Look here http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating for a similar function doing the same thing with a local variable. In this case, the variable would end up globally if it weren't inside the closure.

So there are two things involved:

  • a function to embed variables so they don't become global
  • executing this function immediately to run the code.

Here Immediate functions JavaScript is another discussion about these immediate functions.

All the best, nobi

于 2013-08-19T10:03:10.720 回答
-2

requestAnimationFrame takes one argument: the function to run. However setTimeout takes the function to run as well as a delay after which to run it. So while you can just assign the individual functions directly, you have to create a closure for setTimeout so that you can assign the second argument.

It's basically a form of currying.

于 2012-04-19T22:09:26.193 回答