Reputation: 741
Is there a difference between the two assignments below regarding the bind method? And when is bind necessary, because they do seem to work without bind as well.
option 1
var xxxRequestAnimFrame = foo();
function foo() {
var rAF =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
// if (rAF === undefined) {return undefined;} else {return rAF.bind(window);}
if (rAF === undefined) {return undefined;} else {return rAF;}
}
option 2
var xxxRequestAnimFrame = (function() {
var rAF =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
// if (rAF === undefined) {return undefined} else {return rAF.bind(window);}
if (rAF === undefined) {return undefined} else {return rAF;}
})();
Upvotes: 0
Views: 83
Reputation: 10972
The only difference is that one creates the foo
variable in the enclosing scope. If you're never going to call the function again, it's pointless.
However, you don't need a function at all
var xxxRequestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
No need for .bind()
either unless there's something special you're trying to accomplish.
In particular, this line was needlessly verbose:
if (rAF === undefined) {return undefined} else {return rAF;}
It's equivalent to:
return rAF;
If for some reason you did want to bind window
(though I'm not sure why that would be), I'd do this:
var xxxRequestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
xxxRequestAnimFrame = xxxRequestAnimFrame && xxxRequestAnimFrame.bind(window);
Or if you wanted a no-op function when none is found, and you also wanted to .bind()
, I'd do this:
var xxxRequestAnimFrame = (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame || function(){}).bind(window);
Upvotes: 1