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

4
  • 1
    if the function is in global scope then you can use eval(s+array[i]+ss) - stackoverflow.com/questions/86513/… Commented Aug 28, 2014 at 6:37
  • 1
    But he shouldn't. Use a map of functions, don't define functions in the global scope. Commented Aug 28, 2014 at 6:37
  • 2
    Agree, window[dynamic] is not a solution, nor is eval. This looks like a common XY problem. Commented Aug 28, 2014 at 6:40
  • @dystroy can u tell how to use map of functions Commented Aug 28, 2014 at 6:42

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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"]();

Comments

0

you can use eval function. Eg.

            var s = eval("function get(){}; gat();");

1 Comment

eval function is evil
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.