Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cache eval() result

Tags:

javascript

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();
like image 354
DuduAlul Avatar asked Aug 10 '10 09:08

DuduAlul


People also ask

What is the result of eval?

It returns the completion value of the code. For expressions, it's the value the expression evaluates to.

What is an eval return?

The eval is a part of the JavaScript global object. The return value of eval() is the value of last expression evaluated, if it is empty then it will return undefined .

What does eval method do?

The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

What does eval function do in JavaScript?

The eval() function is used to evaluates the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements. We do not call eval() to evaluate an arithmetic expression. JavaScript evaluates arithmetic expressions automatically.


2 Answers

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);})")
like image 158
Mic Avatar answered Oct 20 '22 00:10

Mic


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.

like image 38
sje397 Avatar answered Oct 19 '22 23:10

sje397