0

I have a funcion whose name is stored in a variable , How can I invoke it?

var fun_name='foo'
0

5 Answers 5

4

If if function is available in global space

window[fun_name]()

If is a member of an object then obj[fun_name]()

Ex:

var obj = {
    foo: function(){}
}
obj[fun_name]()
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that using.

window[fun_name]();

Comments

1

it will also have scope, so simply

scopeVar[fun_name](args);

or if global

window[fun_name](args);

Comments

0

You can use the "eval" function

This will call alert(3)

foo = 'alert(3)';
eval(foo);

Comments

-1

Check this out. How to execute a JavaScript function when I have its name as a string

Or simply use a switch like follows:

switch(fun_name){
case "foo":
foo();
break;
case "foo2":
foo2();
break;
default:
fooDefault();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.