在Javascript中使用动态参数调用动态函数 [英] Calling dynamic function with dynamic parameters in Javascript
问题描述
$ b
function mainfunc(func, par1,par2){
window [func](par1,par2);
}
函数调用函数(par1,par2){
//在这里做东西
}
mainfunc('calledfunc','你好再见');
我知道如何使用arguments []集合传递可选的无限参数main
function mainfunc(func){
if(arguments.length == 3)
window [ func](参数[1],参数[2]);
elseif(arguments.length == 4)
window [func](arguments [1],arguments [2],arguments [3]);
elseif(arguments.length == 5)
window [func](arguments [1],arguments [2],arguments [3],arguments [4]);
}
函数calledfunc1(par1,par2){
//在这里做的东西
}
函数calledfunc2(par1,par2, par3){
//在这里做的东西
}
mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');
使用函数的apply方法: p>
function mainfunc(func){
window [func] .apply(null,Array.prototype.slice.call(arguments ,1));
}
编辑:这发生在我身上稍微调整一下会更有用: -
function mainfunc(func){
this [func] .apply (this,Array.prototype.slice.call(arguments,1));
这可以在浏览器之外工作( this
默认为全局空间)。 mainfunc上的调用也可以使用: -
function target(a){
alert(a)
var o = {
后缀:World,
target:function(s){alert(s + this.suffix); }
};
mainfunc(target,Hello);
mainfunc.call(o,target,Hello);
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');
I know how to pass optional, unlimited parameters using 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]);
elseif(arguments.length == 4)
window[func](arguments[1], arguments[2], arguments[3]);
elseif(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');
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 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");
这篇关于在Javascript中使用动态参数调用动态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!