Problems with the eval function in JavaScript

  • 2020-12-09 00:40:47
  • OfStack

Looking at the code today, I encountered a problem with an eval function. I have read many blog posts until now, but I still don't understand eval function very well. There is a code that I can't understand:


/*
var start = []
 , end = []
 , timings = [];
*/
function f(){
 // Simulate program execution time 
 var sum = 0;
 for(var i =0 ;i < 100000; i++){
  sum = sum/(i+1);
 }
}
function repeat(n, action){
 for(var i=0; i<n ;i++){
  eval(action); // eval function 
 }
}
function benchmark(){
 var start = []
  , end = []
  , timings = [];
 repeat(100, "start.push(new Date().getTime());f();end.push(new Date().getTime())");
 for (var i =0; i< start.length; i++){
  timings[i] = end[i] - start[i];
 }
 return timings;
}
benchmark(); // The results for :[]
// If I take the top one benchmark Move a local variable to a global variable 1 Cut the normal .

If I move the local variable in benchmark above to the global then 1 cut is normal.

Why does the eval function here have this effect? Is this equivalent to aliasing the eval function?

Direct call eval (), it is always in the context of the calling it scope, which means he can access to the variables in repeat function, can't access benchmark variables in functions, but the function is to be able to access to the global scope of variables, so after you set the start those variables into a global variable, and can return the desired results.


function repeat(n, action){
 for(var i=0; i<n ;i++){
  start.push(new Date().getTime());f();end.push(new Date().getTime()); // eval function 
 }
}

The start,end variable cannot be accessed in repeat


Related articles: