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}$" });
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.
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; };
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With