简体   繁体   中英

Passing a function with parameters as a parameter, but which takes the parameter of the invoking function?

How to make this example work?

The idea is to pass as a parameter two functions, which receive internal parameters of the function that receives them as parameter.

function x(a, b, c){
    console.log(a + b + c);
}

function y(a, b, c){
    console.log(a + b + c);
}

function root(param, fn1, fn2){
    var a = a;
    var b = b;
    var c = c

    fn1(a,b,c);
    fn2(a,b,c);
}

root("pm", x(), y());

You can pass values of a,b,c as an array and along with them pass function x and y as parameter to your function

 function x(a, b, c){ console.log(a + b + c); } function y(a, b, c){ console.log(a + b + c); } function root(param, fn1, fn2){ var a = param[0]; var b = param[1]; var c = param[2]; fn1(a,b,c); fn2(a,b,c); } root([1,2,3],x,y); 

I would define it as:

function dual(fn1, fn2, ...params) { // a rest parameter
  fn1(...params); // spread arguments
  fn2(...params);
}

So one can do:

dual(x, y, 1, 2, 3); // pass function references, not function results

Just for fun: You could actually do this with an unlimited amount of functions:

const combine = (...fns) => (...args) => fns.forEach(fn => fn(...args));

combine(x, x, z, z, z)(1, 2, 3)

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