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();
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();
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.
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);})")
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?