Creating functions dynamically

S

Salvatore

Hello,

Given an expression f = '2*x+3' from a user input
I would like to do some sort of

function userFunction(x):
return f(x)

is it possible with Javascript ?


Thanks for your advises

Regards

Salvatore
 
M

Martin Honnen

Salvatore said:
Hello,

Given an expression f = '2*x+3' from a user input
I would like to do some sort of

function userFunction(x):
return f(x)

is it possible with Javascript ?

var fun = new Function("x", f)
 
L

Lasse Reichstein Nielsen

Salvatore said:
Given an expression f = '2*x+3' from a user input
I would like to do some sort of

function userFunction(x):
return f(x)

is it possible with Javascript ?

This is one of the (very few) cases where you might want to
use the eval function (or the comparable Function constructor).

Just remember that the eval/Function functions understand all
javascript, not just arithmetic expressions, so there is plenty
of rope for a user to hang himself with.

Try this:

var userFunction = Function("x","return ("+f+");");

(by wrapping the value of "f" in "return (...)", you guarantee
that "f" contains an expression, not a full Javascript program.
It doesn't change anything for a determined hacker who wants
to execute arbitrary code, but it catches some accidental
mistypings. Remember: *never* use eval for server-side code!)

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top