0

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

var fun_name='foo'
Boaz
  • 19,892
  • 8
  • 62
  • 70
Harikrishnan
  • 9,688
  • 11
  • 84
  • 127

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
  • 384,651
  • 66
  • 527
  • 531
1

You can do that using.

window[fun_name]();
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
1

it will also have scope, so simply

scopeVar[fun_name](args);

or if global

window[fun_name](args);
Tom Carchrae
  • 6,398
  • 2
  • 37
  • 36
0

You can use the "eval" function

This will call alert(3)

foo = 'alert(3)';
eval(foo);
OneSolitaryNoob
  • 5,423
  • 3
  • 25
  • 43
-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