0

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

var fun_name='foo'
Boaz
  • 18,950
  • 8
  • 62
  • 67
Harikrishnan
  • 9,108
  • 9
  • 83
  • 125

5 Answers5

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]()
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
1

You can do that using.

window[fun_name]();
Dipesh Parmar
  • 26,601
  • 7
  • 57
  • 86
1

it will also have scope, so simply

scopeVar[fun_name](args);

or if global

window[fun_name](args);
Tom Carchrae
  • 6,194
  • 2
  • 34
  • 35
0

You can use the "eval" function

This will call alert(3)

foo = 'alert(3)';
eval(foo);
OneSolitaryNoob
  • 5,001
  • 3
  • 21
  • 41
-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();
}

Community
  • 1
  • 1
J5ha
  • 3
  • 3