This question already has an answer here:
这个问题在这里已有答案:
- Calling dynamic function with dynamic parameters in Javascript [duplicate] 10 answers
在Javascript中调用动态参数的动态函数[重复] 10个答案
I have a pre-process function, here's an example function
我有一个预处理函数,这是一个示例函数
function preprocess (msg, fct) {
alert(msg);
fct(???);
}
I need to execute the function fct
in the preprocess
function, but fct
not always has the same number of parameters. I am not a pro in javascript but I think there are 2 ways to achieve that :
我需要在预处理函数中执行函数fct,但是fct并不总是具有相同数量的参数。我不是javascript的专家,但我认为有两种方法可以实现:
-
explicit call with an object
显式调用对象
function preprocess (msg, fct, obj) { ... }
usage : preprocess ('hello', myfct, {firstparam: 'foo', secondparam: 'bar'});
用法:preprocess('hello',myfct,{firstparam:'foo',secondparam:'bar'});
- using the argument inner property of the function
使用函数的参数inner属性
anyways i might have the theory, i am not able to code both the case above. Is it possible to achieve what I need using both the ways ? if yes, could you provide a minimum example of each to show me the way ?
无论如何我可能有理论,我无法编码上述情况。是否有可能使用两种方式实现我需要的东西?如果是的话,你能提供一个最小的例子给我指路吗?
1 个解决方案
#1
You can pass the arguments at the end in variadic form, and use the arguments
object to get what you need:
您可以以可变形式传递最后的参数,并使用arguments对象来获取所需内容:
function preprocess (msg, fct /*, ...as*/) {
var as = [].slice.call(arguments, 2);
alert(msg);
fct.apply(this, as);
}
preprocess(msg, fct, a, b, c); // fct(a, b, c)
#1
You can pass the arguments at the end in variadic form, and use the arguments
object to get what you need:
您可以以可变形式传递最后的参数,并使用arguments对象来获取所需内容:
function preprocess (msg, fct /*, ...as*/) {
var as = [].slice.call(arguments, 2);
alert(msg);
fct.apply(this, as);
}
preprocess(msg, fct, a, b, c); // fct(a, b, c)