以下关于绑定方法的两个作业之间是否存在差异?什么时候需要绑定,因为它们看起来似乎也没有绑定。
选项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;}
}
选项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;}
})();
答案 0 :(得分:1)
唯一的区别是,在封闭范围内创建foo
变量。如果你永远不会再打电话给这个功能,那就毫无意义了。
但是,您根本不需要任何功能
var xxxRequestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
除非你想要完成一些特别的事情,否则不需要.bind()
。
特别是,这条线是不必要的冗长:
if (rAF === undefined) {return undefined} else {return rAF;}
相当于:
return rAF;
如果由于某种原因你确实想绑定window
(虽然我不确定为什么会这样),我会这样做:
var xxxRequestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
xxxRequestAnimFrame = xxxRequestAnimFrame && xxxRequestAnimFrame.bind(window);
或者如果你想找到一个没有操作的功能,你也想要.bind()
,我会这样做:
var xxxRequestAnimFrame = (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame || function(){}).bind(window);