Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Edit Based 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";

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

$(this).rules("add", {mehtodName: "^[a-zA-Z'.\s]{1,40}$" }); 
like image 802
Vaibhav Jain Avatar asked Oct 08 '10 05:10

Vaibhav Jain


People also ask

How do you call a function which is stored in a variable?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a function inside a variable in JavaScript?

we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; };

How do you call a function stored in a variable in Python?

Use getattr() to Assign a Function Into a Variable in Python The function getattr() returns a value of an attribute from an object or module. This function has two required arguments, the first argument is the name of the object or module, and the second is a string value that contains the name of the attribute.

Can a function be stored in a variable?

As we have seen (and will explore more later), functions can be stored in variables. An object is a value in JavaScript that can contain other things: numbers, strings, functions, other objects, etc.


1 Answers

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

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.

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

$(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.

like image 101
mway Avatar answered Oct 20 '22 21:10

mway