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.
这里可以写成
timeShow,"timeShow()",但是不能写成timeShow(),这个参数对于setInterval来说实际上是对timeShow函数的引用,支持以函数名,函数名称字符串的方式,但是timeShow()就不行了,直接使用timeShow()的话这个timeShow函数会直接执行,传给setInterval的参数就不是该函数,而是该函数的返回值了。@王金涛的经纪人
我补充一下。打开控制台敲一下下面的代码:
参考一下 WindowTimers.setTimeout()的描述:
funcA function to be executed after the timer expires.codeAn 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 usingeval()a security risk.此处调取的是函数的指针,只支持3种形态
函数的名称
匿名函数
函数名的字符串
你要记住
foo()表示执行该函数,如果setInterval(foo(), 1000);最终timer执行的是这个foo的return以上三种是官方建议的做法,如果你非要写成
setInterval("a()",1000)这种js的设计缺陷的代码,会给看你代码的人代码不少麻烦。比如:
1+"10"js的
函数的类型很坑,是继承的Object