1

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?

lukas.pukenis
13.7k13 gold badges50 silver badges83 bronze badges
asked Nov 4, 2013 at 16:45
4
  • 1
    I cannot access the actual string What on earth does that mean? Commented Nov 4, 2013 at 16:47
  • 1
    Why can't you use eval? The normal reasons are avoiding it apply to any form of converting strings into program code. Commented Nov 4, 2013 at 16:47
  • @Quentin I forgot to say that I'm coding on a very strict website area. If I get an error, I can't avoid it. If I code undefined(), an unavoidable error will come up. @SLaks I am playing around with window.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. Commented Nov 4, 2013 at 16:56
  • What does "very strict website area" mean? Commented Nov 4, 2013 at 17:37

1 Answer 1

4

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')
answered Nov 4, 2013 at 16:46
Sign up to request clarification or add additional context in comments.

4 Comments

Except ... some restrictions on the website (see comments on question) are not letting me do this. Is there another way?
IN this case my advice is this - create another question and post what do you want to achieve and what do you have. I haven't ever used my method here anywhere in my experience and used eval() just a few times I was lazy writing a parser for math equations so I believe your situation doesn't need neither of those.
@raumaankidwai: What error do you get? If you're getting a CSP error, that means that the website has specifically asked the browser to make it impossible for you to do this.
@SLaks The website doesn't show the KIND of the error, just the error itself. But sometimes, it will say "TypeError: 'undefined' is not a function" or "ReferenceError: rect is not a function`. rect is a function, a built-in function. Here is the link: khanacademy.org/cs/new

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.