简体   繁体   中英

Javascript - passing callback function as argument that would accept any number of accounts

I am asking this question realizing that I would most probably be banned for duplication, but I haven't been able to :

I have a function A that should be able to accept another function B as its argument, but the problem that I can't know in advance the number of arguments of the function B:

function A(callback){
    // wish to call the callback function here
}

function B(x){...};
function C(x, y, z){...};

A(B)
A(C(1,2,3))

Every non arrow function in javascript contains argument object which is local variable within functions and we can pass unlimited number of arguments to javascript functions . You can use arguments object to get arguments of callback function inside callback function. Hence you need not to know exact params, B function is expecting.

function A(callback){
    callback(1,2,3,4............,n arguments)
}

function B(){
   console.log(arguments)
   //iterate over arguments using length property if needed. 
};


A(B)

Second example is when we need to pass arguments along with callback function from A.

function A(callback){
    // Array containing all argument of A including callback function
    //Use ES6 Array.from function to convert arguments object to array to use array functions

    let argumentArray = Array.from(arguments);

    // Splice the array from 1 to end to exclude the first argument of A function i.e. callback function B

    let argumentArrayWithoutCallback = argumentArray.slice(1);

    //Pass this array to callback function

    callback(argumentArrayWithoutCallback)
}

function B(){
   console.log(arguments)
   //iterate over arguments using length property if needed. 
};


A(B,1,2,3.......n)

For more details on arguments object see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM