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
  • 12,081
  • 22
  • 83
  • 117

2 Answers2

1

Please do not use eval.

If the function is in global scope, simply do

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

DEMO

mplungjan
  • 169,008
  • 28
  • 173
  • 236
-2

try this

eval(fn)();

or this

eval(fn + "()");
Naveed Butt
  • 2,861
  • 6
  • 32
  • 55
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • 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