Creating functions dynamically

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Salvatore

    Creating functions dynamically

    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

  • Martin Honnen

    #2
    Re: Creating functions dynamically



    Salvatore wrote:[color=blue]
    > 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 ?
    >[/color]

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

    --

    Martin Honnen


    Comment

    • Lasse Reichstein Nielsen

      #3
      Re: Creating functions dynamically

      Salvatore <artyprog@wanad oo.fr> writes:
      [color=blue]
      > 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 ?[/color]

      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","r eturn ("+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 - lrn@hotpop.com
      Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
      'Faith without judgement merely degrades the spirit divine.'

      Comment

      Working...