在javascript setTimeout中将字符串作为函数运行? [英] Running string as function in javascript setTimeout?

查看:44
本文介绍了在javascript setTimeout中将字符串作为函数运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码有效?

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

不应该吗?

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

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

解决方案

引用 MDN 的 setTimeout 文档

<块引用>

替代语法中的代码是您要在延迟毫秒后执行的代码字符串(不建议使用此语法,原因与使用 eval() 的原因相同)

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

<小时>

这不仅仅是浏览器实现的事情,而且 HTML 规范本身在 本节

<块引用>

handle = window .setTimeout( 代码 [, 超时 ] )

在超时毫秒后安排超时以编译和运行代码.

Why does this code work?

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

Shouldn't it be?

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

How does setTimeout convert string to function?

解决方案

Quoting MDN's 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())

As suggested in the MDN, it is better to avoid strings in the setTimeout as the implementation may eval the string passed.


This is not just a Browser implementation thing, but the HTML specification itself defines it this way in this section

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

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

这篇关于在javascript setTimeout中将字符串作为函数运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆