How do I turn a string into a function?
I've seen "How to turn a String into a javascript function call?" and a few others, but they didn't fit.
I cannot use eval in any way.
I cannot access the actual string. Consider it a predefined string that throws an error when you try to access the value.
SOLUTION QUESTION: Is there a way to NOT use eval and yet make a parseFunction function, like parseInt and parseFloat but with functions?
1 Answer 1
Function constructor accepts a string which defines the function intself, so you can do something like this:
var f = new Function(string);
To call it:
new Function('alert("x");')();
And you will see an alert which displays an x
Passing parameters is defined as this:
new Function(arg1, arg2, argN, functionBody)
So you can pass a string for alert like this:
new Function('arg', 'alert(arg);')('hello')
I cannot access the actual stringWhat on earth does that mean?eval? The normal reasons are avoiding it apply to any form of converting strings into program code.undefined(), an unavoidable error will come up. @SLaks I am playing around withwindow.localStorage. I do NOT know what will come up. @benzonico I haven't tried anything. I don't know what to do. I'm only a beginner.