gpt4 book ai didi

javascript - 当我将其名称作为字符串时如何执行私有(private) JavaScript 函数

转载 作者:行者123 更新时间:2023-11-30 12:51:45 26 4
gpt4 key购买 nike

我正在尝试从返回的对象中执行私有(private)函数。如果我提前知道函数的名称,这很容易,但在这种情况下,我不知道有哪些函数可用。我所拥有的是一个字符串,其中包含要调用的函数的名称。有没有办法通过字符串调用这些函数?

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 函数的最佳方式是什么?感谢您的帮助。

最佳答案

My ideal method for calling but does not work

foo[functionName]();

是的,它试图访问 foo 函数的 [public] 属性。例如,它可以与 "call" 方法一起使用。

This works but I'm trying to avoid eval. I'm not sure if this is not so bad

var func = eval(functionName);
func();

This works. I'm not sure if this is worse than funcRunner2 or the same;

eval(functionName + "()");

eval 的 Angular 来看,两者都一样糟糕。选项 1 只是让使用参数变得更容易 [不需要动态评估]。

This works but requires the exec object which I would like to avoid if at all possible.

exec[functionName]();

这就是实现它的方法。由于 execfoo 范围内的局部变量,您甚至拥有自己的隐私。看来你也为 publicObj 切换了 exec

// I would like to avoid doing this if I don't have to
var publicObj = {};
publicObj.test = function() {
bar();
}

publicObj 变量,尽管它的名字,不是公开的——它是用 var 关键字声明的局部变量!顺便说一句,您可以将其简化为

var exec = {
test: bar
};

关于javascript - 当我将其名称作为字符串时如何执行私有(private) JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20722767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com