The problem _javascript technique of eval function in JavaScript

Source: Internet
Author: User
Tags benchmark

Looking at the code today, the question of an eval function, a lot of blogging now, or the Eval function, there's a code that's never been understood:


/* var start = []
 , end = []
 , timings = [];
/function f () {
 //simulation 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 (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 result is: []
//If I move the local variable in the benchmark above to the global, everything is OK.

If I move the local variable in the benchmark above to the global, everything is OK.

Why does the Eval function here have this effect? Is it the equivalent of aliasing the eval function?

When you call Eval () directly, it is always executed within the context scope in which it is invoked, that is, he can access the variables in the repeat function, and not access the variables in the benchmark function, but in the function is a variable that can access the global scope, So when you set the start variables to global, you can return to 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
 }
}

Start,end variable not accessible in repeat

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.