Cache result eval ()

Can I cache results in Javascript eval?

For example, it would be great if I could:

var str="some code...";
var code = eval(str);
//later on...
code.reExecute();
+5
source share
3 answers

You can make a strfunction body and use New Functioninstead eval.

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

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

Or use eval and do strsomething like

var fn = eval("(function(a){alert(a);})")
+6
source

The result of calling eval is to evaluate javascript. Javascript (in browsers) does not offer any "compilation" function.

The closest you can get (using eval):

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

Then you can call cached_funclater.

+2
source

, - :

 var Cache = { } ;

 function evalString(string) {

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

 }

:

 Cache.evalResult(/* arguments */) ;

On the side of the note is “eval is evil”, as http://www.jslint.com will tell you, since it can open the door for external manipulations of your content. Why do you need evalit to work in the first place?

+1
source

All Articles