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.