gpt4 book ai didi

javascript - 在javascript setTimeout中将字符串作为函数运行?

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:21 26 4
gpt4 key购买 nike

为什么这段代码有效?

setTimeout("document.body.innerHTML = 'TEST'", 1000)

不应该吗?

setTimeout(function() {
document.body.innerHTML = 'TEST'
}, 1000)

setTimeout如何将字符串转为函数?

最佳答案

引用 MDN 的 setTimeout documentation

code in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using eval())

如 MDN 中所建议,最好避免在 setTimeout 中使用字符串,因为实现可能会eval 传递的字符串。


这不仅仅是浏览器实现的事情,而是 HTML 规范本身在 this section 中以这种方式定义它

handle = window . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

关于javascript - 在javascript setTimeout中将字符串作为函数运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com