i am generating dynamic javascript in which i create few functions for storing value
function get[dynamicname](){
return "some value";
}
i want to call this method in another function to get the values of all functions i created
i have all the dynamicnames which i used to create the functions in the function which i am calling..
function getallfunctionvals(){
for ( var i = 0; i < array.length; i++ ) {
var s="get";
var ss="()";
console.log(s+array[i]+ss);
}
}
this is how i am calling the dynamically generated functions but in the console i am getting the function name as string not the value inside it
4 Answers 4
Hi look at This post.
One of the answer:
if you know that its a global function you can use:
var functPtr = window[func_name];
//functPtr()
Otherwise replace window with the parent object containing the function.
Comments
if defined function is in gloabal scope, you can use
window[s+array[i]]()
So if you have a function like getName. what it will do it will call something like
window["getName"]();
Comments
you can use eval function. Eg.
var s = eval("function get(){}; gat();");
1 Comment
first of all:
function get[dynamicname](){
return "some value";
}
will generate error: SyntaxError: Unexpected token [
Since "[" is not allowed in javascript function name and variable.
But you can do this:
function getName () {console.log('Name')};
function getAge () {console.log('Age')};
When you invoke the above functions, you can do this:
var s="get";
var thingToGet = "Name";
var ss="()";
eval(s + thingToGet + ss)
Did I answer your question?
eval(s+array[i]+ss)- stackoverflow.com/questions/86513/…window[dynamic]is not a solution, nor iseval. This looks like a common XY problem.