0

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

Sarbbottam
  • 5,410
  • 4
  • 30
  • 41
Vijay Rahul
  • 103
  • 1
  • 2
  • 11

4 Answers4

1

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.

Community
  • 1
  • 1
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

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"]();
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

you can use eval function. Eg.

            var s = eval("function get(){}; gat();");
Vicky
  • 603
  • 5
  • 6
0

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?

Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129