【发布时间】:2013-12-21 19:33:28
【问题描述】:
我正在尝试从返回的对象中执行一个私有函数。如果我提前知道函数的名称,这很容易,但在这种情况下,我不知道有哪些函数可用。我所拥有的是带有要调用的函数名称的字符串。有没有办法通过字符串调用这些函数?
function foo() {
// some misc. chunk of valid javascipt code
function bar() {
console.log("hello");
}
// end misc. code
// I would like to avoid doing this if I don't have to
var executableFn = {};
executableFn.test = function() {
bar();
}
// end
return {
// This works but requires I know the name of the funciton ahead of time.
// All I have is a string name of the function to call.
funcRunner0: function() {
bar();
},
// My ideal method for calling but does not work
funcRunner1: function(functionName) {
foo[functionName]();
},
// This works but I'm trying to avoid eval. I'm not sure if this is not so bad
funcRunner2: function(functionName) {
var func = eval(functionName);
func();
},
// This works. I'm not sure if this is worse than funcRunner2 or the same;
funcRunner3: function(functionName) {
eval(functionName + "()");
},
// This works but requires the executableFn object which I would like to avoid if at all possible.
funcRunner4: function(functionName) {
executableFn[functionName]();
},
};
}
var bas = foo();
// This works but assumes I know the name of the function to call which I don't.
bas.funcRunner0();
// This doesn't work
bas.funcRunner1("bar");
// This works
bas.funcRunner2("bar");
// This works
bas.funcRunner3("bar");
// This works but is not my ideal
bas.funcRunner4("test");
这些都是我想出的调用这个函数的方法。您认为我用字符串调用 bar 函数的最佳方法是什么?谢谢你的帮助。
【问题讨论】:
标签: javascript private