使用动态数量的参数调用动态函数 [英] Calling dynamic function with dynamic number of parameters
问题描述
我正在寻找一个窍门.我知道如何在JavaScript中调用动态的任意函数,并传递特定的参数,例如:
I’m looking for a trick about this. I know how to call a dynamic, arbitrary function in JavaScript, passing specific parameters, something like this:
function mainfunc(func, par1, par2){
window[func](par1, par2);
}
function calledfunc(par1, par2){
// Do stuff here
}
mainfunc('calledfunc', 'hello', 'bye');
我知道如何使用mainfunc
内的arguments
集合传递可选的,无限制的参数,但是,我不知道如何将任意数量的参数发送到mainfunc
以动态发送到calledfunc
;我该如何完成这样的工作,但是要有任意数量的可选参数(不要使用难看的if
– else
)?
I know how to pass optional, unlimited parameters using the arguments
collection inside mainfunc
, but, I can’t figure how to send an arbitrary number of parameters to mainfunc
to be sent to calledfunc
dynamically; how can I accomplish something like this, but with any number of optional arguments (not using that ugly if
–else
)?
function mainfunc(func){
if(arguments.length == 3)
window[func](arguments[1], arguments[2]);
else if(arguments.length == 4)
window[func](arguments[1], arguments[2], arguments[3]);
else if(arguments.length == 5)
window[func](arguments[1], arguments[2], arguments[3], arguments[4]);
}
function calledfunc1(par1, par2){
// Do stuff here
}
function calledfunc2(par1, par2, par3){
// Do stuff here
}
mainfunc('calledfunc1', 'hello', 'bye');
mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');
推荐答案
使用函数的apply方法:-
Use the apply method of a function:-
function mainfunc (func){
window[func].apply(null, Array.prototype.slice.call(arguments, 1));
}
编辑:在我看来,只要稍加调整,它就会更加有用:-
Edit: It occurs to me that this would be much more useful with a slight tweak:-
function mainfunc (func){
this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}
这将在浏览器之外工作(this
默认为全局空间).在mainfunc上使用call也会起作用:-
This will work outside of the browser (this
defaults to the global space). The use of call on mainfunc would also work:-
function target(a) {
alert(a)
}
var o = {
suffix: " World",
target: function(s) { alert(s + this.suffix); }
};
mainfunc("target", "Hello");
mainfunc.call(o, "target", "Hello");
这篇关于使用动态数量的参数调用动态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!