0

Consider I have a name of a function which does not require any argument in a var -

var fn = "foo";

Can I execute it in some or similar like this -

eval(fn);

It does not work. Please suggest.

My definition of function will look like this -

function foo() {
  ....do something....
}
Ashwin
  • 11,415
  • 20
  • 77
  • 115

2 Answers2

1

Please do not use eval.

If the function is in global scope, simply do

var fn = "foo";
window[fn]();

DEMO

mplungjan
  • 155,085
  • 27
  • 166
  • 222
-2

try this

eval(fn)();

or this

eval(fn + "()");
Naveed Butt
  • 2,732
  • 6
  • 29
  • 52
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
  • 1
    eval is considered evil. It will work but is not necessary and should be avoided – mplungjan Apr 24 '13 at 05:04
  • 1
    @mplungjan, I guess I know you from EE days :). Anyways, eval is evil if the string to be evaluated is entered by user, otherwise it should be fine barring the fact that string will be compiled and then executed. – gurvinder372 Apr 24 '13 at 05:10
  • 1
    Sure - but it is better to never use it than to use it instead of a more appropriate method - and yes, we know each other ;) – mplungjan Apr 24 '13 at 05:12