这段代码是作为previous question流量控制的工作解决方案提供的:
// an object to maintain a list of functions that can be called in sequence
// and to manage a completion count for each one
function Sequencer() {
this.list = [];
this.cnt = 0;
}
Sequencer.prototype.add = function(/* list of function references here */) {
this.list.push.apply(this.list, arguments);
}
Sequencer.prototype.next = function() {
var fn = this.list.shift();
if (fn) {
fn(this);
}
}
Sequencer.prototype.increment = function(n) {
n = n || 1;
this.cnt += n;
}
// when calling .decrement(), if the count gets to zero
// then the next function in the sequence will be called
Sequencer.prototype.decrement = function(n) {
n = n || 1;
this.cnt -= n;
if (this.cnt <= 0) {
this.cnt = 0;
this.next();
}
}
// your actual functions using the sequencer object
function test_1(seq, arg1, arg2, arg3) {
seq.increment();
// do something with arg1, arg2 and arg3
seq.decrement();
}
function test_2(seq) {
seq.increment();
// do something
seq.decrement();
}
function test_3(seq) {
seq.increment();
// do something
seq.decrement();
}
// code to run these in sequence
var s = new Sequencer();
// add all the functions to the sequencer
s.add(test_1, test_2, test_3);
// call the first one to initiate the process
s.next();
在将函数添加到test_1()
时,如何将参数传递给s
?例如(显然不起作用):
s.add(test_1(10,'x',true), test_2);
由于
答案 0 :(得分:2)
如果订单不同,即test_1(arg1, arg2, arg3, seq)
,您可以使用.bind
:
s.add(test_1.bind(null, 10,'x',true) , test_2, test_3);
如果您无法更改订单,请传递其他功能,然后再调用test_1
:
s.add(function(seq) { test_1(seq, 10,'x',true); }, test_2, test_3);
答案 1 :(得分:0)
您可以使用Function.arguments
访问函数的给定参数。