javascript - cache eval() result - Stack Overflow

In Javascript, is it possible to cache the results of eval?For example it would be great if I could:var

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
Add a ment  | 

3 Answers 3

Reset to default 5

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

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745397425a4625943.html

相关推荐

  • javascript - cache eval() result - Stack Overflow

    In Javascript, is it possible to cache the results of eval?For example it would be great if I could:var

    12小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信