javascript - `setTimeout` ,通过字符串传递,返回错误

标签 javascript html css

<分区>

这是两段相同的代码;但第一个工作正常:

function dismiss(obj) {setTimeout(function() {obj.style.display = "none";}, 20);}

而第二个返回error: obj is not defined:

function dismiss(obj) {setTimeout('obj.style.display = "none"', 20);}

为什么会这样?
附言: An example

最佳答案

答案就在closures , or more in depth .

在第一个示例中,obj 变量在创建匿名函数时被捕获。当函数运行时,捕获的 obj 引用用于访问 style,效果很好。

但是在第二个中,没有闭包,因为字符串是通过 eval inside setTimeout 运行的,如 Mozilla documentation 中所述, 将在全局上下文中执行:

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.

全局上下文不包含obj变量,导致“未定义”错误。

关于javascript - `setTimeout` ,通过字符串传递,返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744678/

相关文章:

javascript - 如何修复运行 'cannot find module'错误的Docker容器?

javascript - 样式化 jQuery 验证错误消息

javascript - 表格内容不在下方

html - CSS3 中闪烁的灯光(点击)动画

javascript - HTML/CSS float left 自动填充空白

javascript - ionic /javascript : text with < a > tag can't be clicked in the HTML

javascript - 我想在 useEffect 中使用异步函数,但它不起作用

javascript - 如果 JSON 对象位于嵌套数组中,如何使用 Mustache.js?

html - 为移动应用程序生成 UI

javascript - Typo3 - 如何在合并文件中包含所有 CSS 和 JS 文件