簡體   English   中英

將參數傳遞給函數原型

[英]Passing argument to function prototype

這段代碼是作為先前關於流量控制問題的工作解決方案提供的:

// 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();

將函數添加到s時,如何將參數傳遞給test_1() 例如(這顯然不起作用):

s.add(test_1(10,'x',true), test_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);

您可以使用Function.arguments訪問函數的給定參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM