javascript 如何使用存储在变量中的值调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3887885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:34:02  来源:igfitidea点击:

How to call function using the value stored in a variable?

javascriptjqueryfunction

提问by Vaibhav Jain

I have a variable

我有一个变量

var functionName="giveVote";

What I need to do is, I want to call function stored in var functionName. I tried using functionName(); . But its not working. Please help.

我需要做的是,我想调用存储在var functionName 中的函数。我尝试使用 functionName(); . 但它不工作。请帮忙。

EditBased on the same problem, I have

编辑基于同样的问题,我有

$(this).rules("add", {txtInf: "^[a-zA-Z'.\s]{1,40}$" }); 

rules is a predifined function which takes methodName:, here I have hardcoded txtInf. But I want to supply a javascript variable here, to make my code generic. var methodName="txtInf";

rules 是一个预定义的函数,它采用 methodName:,这里我硬编码了 txtInf。但我想在这里提供一个 javascript 变量,以使我的代码通用。 var methodName="txtInf";

Here I want to evaluate methodName first before being used in rules function.

这里我想在用于规则函数之前先评估 methodName。

$(this).rules("add", {mehtodName: "^[a-zA-Z'.\s]{1,40}$" }); 

回答by mway

You have a handful of options - two basic ones include window[functionName]()or setTimeout(functionName, 0). Give those a shot.

您有几个选项 - 两个基本选项包括window[functionName]()setTimeout(functionName, 0)。试一试吧。

Edit: if your variable is just the string name of a function, use those; otherwise, if you're able to actually assign a function reference to the variable (eg, var foo = function() {};), you could use the foo()notation, or foo.apply(this, []), etc.

编辑:如果您的变量只是函数的字符串名称,请使用它们;否则,如果您能够实际将函数引用分配给变量(例如,var foo = function() {};),则可以使用foo()符号或foo.apply(this, [])等。

Edit 2: To evaluate methodNamein place prior to $(this).rules()firing, you'd just apply the first syntax above (using the windowobject), like so:

编辑 2:要methodName$(this).rules()触发之前就地进行评估,您只需应用上面的第一个语法(使用window对象),如下所示:

$(this).rules("add", {window[methodName](): ...});

I think that's what you're asking - if not, please clarify a bit more and I'll be happy to rewrite a solution.

我认为这就是您要问的 - 如果不是,请多澄清一点,我很乐意重写解决方案。

回答by Nivas

   var functionName="giveVote"; 

Assigns the String "giveVote" to the variable functionName. If giveVote is the name of the function, then you have to assignin one of the following ways:

将字符串“giveVote”分配给变量 functionName。如果 giveVote 是函数的名称,那么您必须通过以下方式之一进行分配

If you know the function name at compile time, then you can

如果你在编译时知道函数名,那么你可以

var functionName="giveVote"; 

But I think you want to dynamicallyassign the function and then call it. Then you have to say

但我认为你想动态分配函数然后调用它。那你得说

   var functionName=window["giveVote"]; 

and then call it by

然后调用它

functionName();

Or directly

或者直接

window["giveVote"]();

This is possible because any global function you declare in JavaScript (global as in not part of any other object), then it becomes part of the windowobject.

这是可能的,因为您在 JavaScript 中声明的任何全局函数(全局,不属于任何其他对象的一部分),然后它就成为window对象的一部分。

回答by Kartik

From what I understand you have the function's name stored in the variable functionName. Now this is different from holding a reference to the function itself. So, you cannot just use functionName(), because functionName refers to a String object here, not a function.

据我了解,您将函数名称存储在变量functionName 中。现在这与持有对函数本身的引用不同。因此,您不能只使用 functionName(),因为 functionName 在这里指的是 String 对象,而不是函数。

So, here's what you need to do, use the functionName to get the function object. As suggested above you can use window[functionName] if the function has been defined in the window scope. But in based on how your code is structured you would most probably have this function as a member of some other object, and you would need to use that object to access the function. For example, if variable objContainingFunctionrefers to an object that contains the function with the name defined in functionName, then you could call the function using

所以,这就是你需要做的,使用 functionName 来获取函数对象。如上所述,如果函数已在窗口范围内定义,您可以使用 window[functionName]。但是根据您的代码的结构,您很可能会将这个函数作为某个其他对象的成员,并且您需要使用该对象来访问该函数。例如,如果变量objContainingFunction引用的对象包含具有在functionName 中定义的名称的函数,那么您可以使用

objContainingFunction[functionName]( ).

objContainingFunction[functionName]()

And regarding your edit -

关于您的编辑 -

$(this).rules("add", {mehtodName: "^[a-zA-Z'.\s]{1,40}$" });

$(this).rules("add", {mehtodName: "^[a-zA-Z'.\s]{1,40}$" });

What exactly is your requirement here? Because, as I mentioned earlier, methodName is a string here.

您在这里的具体要求是什么?因为,正如我之前提到的,methodName 在这里是一个字符串。

回答by JasCav

Why not just pass the string directly to where you want to call the function? Why store it first? That seems more confusing as it is another layer of indirection (and, ultimately, can make your code more difficult to debug).

为什么不直接将字符串传递到要调用函数的位置?为什么要先存储?这似乎更令人困惑,因为它是另一层间接(并且最终会使您的代码更难以调试)。

For example:

例如:

$('.someSelector').click(giveVote);

I don't see a particular advantage to doing what you're trying to do.

我没有看到做你想做的事情有什么特别的好处。

回答by Justin Johnson

There normally isn't a good reason for using a string to pass a function reference around. If you need to do this, just assign the function to a variable. Since functions are objects, it's really just as easy as treating them like any other variable.

通常没有充分的理由使用字符串来传递函数引用。如果您需要这样做,只需将该函数分配给一个变量。因为函数是对象,所以就像对待任何其他变量一样简单。

var giveVote = function() { ... };

var someOtherFunction = function(callback) {
    callback();
};

someOtherFunction(giveVote);

On a related note, setTimeout(functionName, 0)only works because setTimeout will evalthe first parameter if it is a string. It's best to avoid this for performance and security concerns.

在相关说明中,setTimeout(functionName, 0)仅适用于 setTimeout 将eval是字符串的第一个参数。出于性能和安全考虑,最好避免这种情况。

回答by ScrapCode

I agree with the solution provided by Justin, adding one more scenario here.

我同意 Justin 提供的解决方案,并在此处添加更多场景。

You can even take the callback function name stored in some object & then call it.

您甚至可以获取存储在某个对象中的回调函数名称,然后调用它。

e.g.

例如

var callback =  this.objName.getHandlerName() ; //we get the current function to call from some logic

callback(); //actual call to the function