简体   繁体   English

将带有参数的函数作为参数传递,但是哪个参数需要调用函数的参数?

[英]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 您可以将a,b,c的值作为数组传递,并与它们一起将函数x和y作为参数传递给函数

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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