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();
It returns the completion value of the code. For expressions, it's the value the expression evaluates to.
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 .
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.
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.
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 'compile' function.
The closest you could get (using eval) is:
var cached_func = eval('function() {' + str + '}');
Then you can call the cached_func
later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With