图中箭头指的地方要不要写成timeShow(),或者"timeShow()"
好像都可以运行,那么加括号或双引号有什么区别吗?
这里可以写成timeShow
,"timeShow()"
,但是不能写成timeShow()
,这个参数对于setInterval
来说实际上是对timeShow
函数的引用,支持以函数名,函数名称字符串的方式,但是timeShow()
就不行了,直接使用timeShow()
的话这个timeShow函数会直接执行,传给setInterval的参数就不是该函数,而是该函数的返回值了。
我补充一下。打开控制台敲一下下面的代码:
function foo() {
console.log('outer foo')
}
function test() {
function foo() {
console.log('inner foo')
}
setTimeout(foo, 1000);
setTimeout('foo()', 2000);
}
test();
参考一下 WindowTimers.setTimeout()的描述:
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code[, delay]);
var timeoutID = window.setTimeout(function, milliseconds);
func
A function to be executed after the timer expires.
code
An optional syntax allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval()
a security risk.
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
5 回答1.9k 阅读
此处调取的是函数的指针,只支持3种形态
函数的名称
匿名函数
函数名的字符串
你要记住
foo()
表示执行该函数,如果setInterval(foo(), 1000);
最终timer执行的是这个foo
的return
以上三种是官方建议的做法,如果你非要写成
setInterval("a()",1000)
这种js的设计缺陷的代码,会给看你代码的人代码不少麻烦。比如:
1+"10"
js的
函数
的类型很坑,是继承的Object