By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,382 Members | 1,631 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,382 IT Pros & Developers. It's quick & easy.

Creating functions dynamically

P: n/a
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

Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a


Salvatore wrote:
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)

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2

P: n/a
Salvatore <ar******@wanadoo.fr> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.