最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - cache eval() result - Stack Overflow

programmeradmin1浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论