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();
Share
Improve this question
edited Sep 22, 2011 at 13:43
Richard JP Le Guen
28.7k8 gold badges93 silver badges120 bronze badges
asked Aug 10, 2010 at 9:33
DuduAlulDuduAlul
6,4007 gold badges43 silver badges63 bronze badges
3 Answers
Reset to default 5You 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);})")
The result of the 'eval' call is to evaluate the javascript. Javascript (in browsers) does not offer any kind of 'pile' function.
The closest you could get (using eval) is:
var cached_func = eval('function() {' + str + '}');
Then you can call the cached_func
later.
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. 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?