The difference between eval and setTimeout is done using string code

I know that evalu setTimeoutcan take a string as a parameter (1st), and I know that it’s better not to use this. I'm just wondering why there is a difference:

!function() {
    var foo = 123;
    eval("alert(foo)");
}();

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

the first will work, and the second will give an error: foo is not defined

How are they performed behind the scenes?

+5
source share
5 answers

See link setTimeoutto MDN .

String literals are evaluated in a global context, so local characters in the context where the setTimeout () method was called will not be available if the string is evaluated as code.

In contrast, the string literal passed to eval () is executed in the context of the call to eval.

+4
source

setTimeout eval , foo.

:

, , setTimeout(), .

+2

setTimeout , -. , , .

setTimeout(myFunction(param1, param2), 0, param1, param2);
+1
!function() {
    var foo = 123;
    eval("alert(foo)");
}();

javascript , 3 "alert (foo)". Foo .

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

When executing this code, javascript introduces a new function; viz function() {alert(foo)}. This "new" function is foonot defined.

0
source

As a complement to the correct answer, here is a call to evalwhich will give you the same behavior and error in this case:

!function() {
    var foo = 123;
    window.eval("alert(foo)"); // <- note the window.eval, this is important and changes the behavior of the `eval` function
}();

!function() {
    var foo = 123;
    setTimeout("alert(foo)", 0);
}();

This blog post details the various types eval: http://perfectionkills.com/global-eval-what-are-the-options/

0
source

All Articles