tags:

views:

54

answers:

3

In Javascript, is it possible to cache the results of eval.

For example it would be great if I could:

var str="some code...";
var code = eval(str);
//later on...
code.reExecute();
+2  A: 

The result of the 'eval' call is to evaluate the javascript. Javascript (in browsers) does not offer any kind of 'compile' function.

The closest you could get (using eval) is:

var cached_func = eval('function() {' + str + '}');

Then you can call the cached_func later.

sje397
how about not in browsers?
WSimpleGuy
See [here](http://code.google.com/apis/v8/get_started.html) for an example of using `Script::Compile` with Google's V8 JavaScript engine.
sje397
+4  A: 

You can make str the body of a function and use New Function instead of eval.

var fn = new Function([param1, param2,...], str);

And reuse it by calling fn(p1, p2,...)

Or use eval, and make str be something like

var fn = eval("(function(a){alert(a);})")
Mic
This. Although it's slightly different to `eval` in that the code in the string does not inherit the local scope of the containing code.
bobince
@bobince, I was just editing it
Mic
It seems like both answers use ALMOST the same way to do it, great!is there any performance benchamark which exact method (1- creating new function with a string, 2- eval a function) is better?
WSimpleGuy
I moved from eval to new Function in the first release of a JS lib I did(PURE) and did not notice any performance improvement. However the comment of bobince is the one that needs to drive your choice, if the parameters you pass to the function are always the same, you can use New Function otherwise use eval. Are you sure you want to use eval? In the current version of PURE, by trying harder, we suppressed both evil methods. Ok... this is another debate :)
Mic
+1  A: 

Make a function that evaluates and stores the result in a cache object for asynchronous retrieval:

 var Cache = { } ;

 function evalString(string) {

     var evaluated = eval(string) ;
         Cache.evalResult = evaluated ;

 }

You may then call that code like this:

 Cache.evalResult(/* arguments */) ;

On a side note, "eval is evil" as http://www.jslint.com will tell you, since it may open the door for external manipulation of your content. Why do you need to eval that function it in the first place?

FK82
I have a string that has to be evaluated...
WSimpleGuy