Home >Web Front-end >JS Tutorial >Problems with eval function in JavaScript_javascript skills

Problems with eval function in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:16:481288browse

Looking at the code today, I encountered a problem with the eval function. I have read a lot of blog posts, but I still don’t understand the eval function very well. There is a code that I still can’t understand as follows:

/*
var start = []
 , end = []
 , timings = [];
*/
function f(){
 //模拟程序执行时间
 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 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(); //结果为:[]
//如果我把上面的benchmark中的局部变量移到全局就一切正常.

If I move the local variables in the above benchmark to the global, everything works fine.

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

When eval() is called directly, it is always executed within the context scope of calling it, which means that it can access the variables in the repeat function, but cannot access the variables in the benchmark function, but it can be accessed in the function. Access to variables in the global scope, so after you set the start variables to global variables, you 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函数
 }
}

The start and end variables cannot be accessed in repeat

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn