Javascript 通过fn.apply或fn.bind将函数传递给setTimeout
为了限制对API的请求,我提出了一种方法,在每个间隔中只允许一定数量的请求 它可以工作,但我想假装检查Javascript 通过fn.apply或fn.bind将函数传递给setTimeout,javascript,node.js,Javascript,Node.js,为了限制对API的请求,我提出了一种方法,在每个间隔中只允许一定数量的请求 它可以工作,但我想假装检查setTimeout部分 我尝试了setTimeout(fn.apply,self.sleepTime(),null,fn_参数)和setTimeout(fn.bind(fn_参数),self.sleepTime()) 因此,我想知道的是,我是否可以将fn传递给setTimeout,而无需将其包装在函数中 function (fn) { var self = this; return f
setTimeout
部分
我尝试了setTimeout(fn.apply,self.sleepTime(),null,fn_参数)
和setTimeout(fn.bind(fn_参数),self.sleepTime())
因此,我想知道的是,我是否可以将fn
传递给setTimeout
,而无需将其包装在函数中
function (fn) {
var self = this;
return function () {
var fn_arguments = arguments;
setTimeout(function () {
fn.apply(null, fn_arguments);
}, self.sleepTime());
};
};
测试:
var-args;
函数fn(){
write(JSON.stringify(参数),“~”,JSON.stringify(参数)==JSON.stringify(参数));
文件。写(“
”);
}
(功能(){
args=参数;
fn('hello','world');/{'0':'hello','1':'world'}✓
fn.bind.apply(fn[null].concat(arguments))();//{0':{0':'hello','1':'world'}
fn.bind.apply(fn,Array.prototype.slice.call(arguments))();/{0':'world'}
fn.bind.apply(fn[null].concat(Array.prototype.slice.call(arguments))();/{0':'hello','1':'world'}✓
}(“你好”,“世界”)代码>您可以使用bind创建一个包含函数参数的函数,并在setTimout调用中使用它。但是,bind不接受单个参数数组,而是接受多个逗号分隔的参数。要解决此问题,可以调用bind函数的apply,如下所示:
setTimeout(fn.bind.apply(fn, [null].concat(fn_arguments)), self.sleepTime())
编辑:您必须确保fn_arguments
是一个数组,例如通过var fn_arguments=array.prototype.slice.call(arguments)转换arguments对象代码>关闭!您只需结合第二步和第三步:
fn.bind.apply(fn, [null].concat(Array.prototype.slice.call(arguments)))();
你想现在做什么?我可以将fn
传递给setTimeout
,而不将其包装在函数中吗?如果你想包含这样的参数,我就不需要了。我从未在规范中见过“feinschmecker”,确切地说,这是对函数的什么操作?feinschmecker是“改进”的俚语:)对不起,我不能让它工作。检查我上面添加的可运行代码段。您的回答给了我{“0”:{“0”:“你好”,“1”:“世界”}
您必须确保fn_参数
是一个数组。传递arguments对象无效。在示例代码中,使用fn.bind.apply(fn[null].concat(Array.prototype.slice.call(arguments))()代码>