I know that eval and setTimeout can both accept a string as the (1 st) parameter, and I know that I’d better not use this. I’m just curious why is there a difference:
!function() {
var foo = 123;
eval("alert(foo)");
}();
!function() {
var foo = 123;
setTimeout("alert(foo)", 0);
}();
the first would work, and the second will give an error: foo is not defined
How are they executed behind the scene?
See the reference of
setTimeouton MDN.In contrast, the string literal passed to eval() is executed in the context of the call to eval.