1

Why do we bother creating an anonymous function block, which is immediately evaluated, as in the following (a common JS idiom I see)?

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

Instead why not use a more direct route as below?

window.requestAnimFrame = 
          window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
          };
wcochran
  • 10,089
  • 6
  • 61
  • 69
  • In this case it really doesn't make a difference but maybe the writer wanted to prepare for using local variables inside the anonymous function sometime in the futur. Anyway, the main reason to use this pattern is scoping of which this particular example doesn't make use. – basilikum Aug 09 '13 at 16:41
  • @basilikum -- yes, hiding local variables in a block makes sense. This snippet of code is a frequently used boilerplate and I don't see folks defining new local vars -- but that must be it. – wcochran Aug 09 '13 at 16:51

1 Answers1

2

There is no reason in the above code, as you don't have any local variables in the anonymous function. It could be reasonable, but definitely not necessary, to make use of it to shorten your code a bit though. For example:

window.requestAnimFrame = (function(w){
  return  w.requestAnimationFrame       || 
          w.webkitRequestAnimationFrame || 
          w.mozRequestAnimationFrame    || 
          w.oRequestAnimationFrame      || 
          w.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element){
             w.setTimeout(callback, 1000 / 60);
          };
})(window);
Paul
  • 139,544
  • 27
  • 275
  • 264
  • Sure, but the code I gave seems to be the universal boilerplate. Far be it from me to deviate from it. :) I guess this has been asked before : http://stackoverflow.com/questions/10237471/please-explain-this-requestanimationframe-idiom – wcochran Aug 09 '13 at 16:53