gpt4 book ai didi

javascript - 是否需要绑定(bind)方法?

转载 作者:行者123 更新时间:2023-12-03 12:24:27 25 4
gpt4 key购买 nike

下面关于绑定(bind)方法的两个赋值之间有区别吗?何时需要绑定(bind),因为它们似乎在没有绑定(bind)的情况下也能工作。

选项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;}
})();

最佳答案

唯一的区别是在封闭范围内创建 foo 变量。如果您永远不会再次调用该函数,则毫无意义。

但是,您根本不需要函数

var xxxRequestAnimFrame = window.requestAnimationFrame   ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;

也不需要.bind(),除非您想要完成一些特殊的事情。

<小时/>

特别是,这一行不必要地冗长:

if (rAF === undefined) {return undefined} else {return rAF;}

相当于:

return rAF;
<小时/>

如果由于某种原因你确实想绑定(bind)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);

关于javascript - 是否需要绑定(bind)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24274616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com