PDA

View Full Version : javascript eval() function, and defining new functions




Oats
Nov 28, 2006, 08:38 AM
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:

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:

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:

evalstr = "function f(x) { return (x*x/2) }; f(10)";
result = eval(evalstr);

any advice?
thanks!



robbieduncan
Nov 28, 2006, 09:10 AM
eval("g=function f(x) {alert(x)}");
eval("g(2)");


Works for me in FireFox at least.