javascript: 传递/接受参数给 func

javascript: pass / accept params to func

我在 javasciprt 有通用函数。 它接受:要调用的其他功能和要发送的参数。 看起来像:

    function generic(func, funcArguments){
       //my Code...
       func(funcArguments);
    }

假设我从名为 myFunc 的函数调用通用函数:

   function myFunc(a, b){
        generic(foo, arguments);//argument will pass a and b, as js rules
   }


   function foo(a, b){
       ///my code
   }

结果是 foo 将所有参数作为一个实体传递给参数 a。

这对我不好。 我需要它接受 a 到 a 和 b 到 b。 但是我不能简单地发送它们,因为每次我都接受参数的差异计数。

有没有办法实现这个逻辑?

您需要调用方法 will apply(context, arguments)。然后参数将作为参数数组的单独成员提供,而不是只有一个参数。

function generic(func, funcArguments){
   func.apply(this, funcArguments);
}