Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Oats

macrumors regular
Original poster
Jan 8, 2003
194
1
New York
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!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.