eval和setTimeout之间的差异执行字符串代码 [英] Difference between eval and setTimeout execute string code
问题描述
我知道 eval
和 setTimeout
都可以接受字符串作为(第一个)参数,而我知道我最好不要用它。我只是好奇为什么会有区别:
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);
}();
第一个会起作用,第二个会产生错误: foo is未定义
the first would work, and the second will give an error: foo is not defined
如何在幕后执行?
推荐答案
参见 setTimeout
的引用。
在全局上下文中计算字符串文字,因此当字符串被计算为代码时,调用setTimeout()的上下文中的局部符号将不可用。
String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.
相反,字符串文字传递给 eval( )在eval调用的上下文中执行。
In contrast, the string literal passed to eval() is executed in the context of the call to eval.
这篇关于eval和setTimeout之间的差异执行字符串代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!