javascript eval() function, and defining new functions

Discussion in 'Mac Programming' started by Oats, Nov 28, 2006.

  1. Oats macrumors regular

    Joined:
    Jan 8, 2003
    Location:
    New York
    #1
    hello-
    i am working on a dashboard widget, and have a fundamental? question about how the "eval" function works. in javascript, it is quite powerful to evaluate a formula, defined in a string. eval() can also use and define new variables, for example:

    Code:
    eval("g = 52");
    this line will define a new variable g, equal to 52, which can be used in subsequent eval calls, or later on in the script.

    the problem i am having is i would like to define a function during one call to eval(), and reference that function in a later call to eval(), such as the following:

    Code:
    evalstr = "function f(x) { return (x*x/2) }";
    result = eval(evalstr);
    evalstr = "f(10)";
    result = eval(evalstr);
    f(10) should evaluate to 10*10/2 = 50, however this does not work. the function definition is lost by the time the second eval() is called. the function definition is fine if i separate both calls with a semicolon, but this is not useful to me in my application:

    Code:
    evalstr = "function f(x) { return (x*x/2) }; f(10)";
    result = eval(evalstr);
    any advice?
    thanks!
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Code:
    eval("g=function f(x) {alert(x)}");
    eval("g(2)");
    
    Works for me in FireFox at least.
     

Share This Page