Skip to content Skip to sidebar Skip to footer

Is There A Way To Execute A Function When I Have Its Name In A String

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.

Solution 1:

Please do not use eval.

If the function is in global scope, simply do

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

DEMO

Solution 2:

try this

eval(fn)();

or this

eval(fn + "()");

Post a Comment for "Is There A Way To Execute A Function When I Have Its Name In A String"