我怎么能说:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
为什么函数会调用setTimeout
不需要括号,但最后一行需要吗?
Nutshell
-
myFunction
引用函数
-
myFunction()
调用函数
更多单词
setTimeout
expects a function reference* as an argument.
有些情况下setTimeout(myFunction(), 1000)
可能有道理,就像如果myFunction()
返回一个函数,例如
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
-
setTimeout
得到返回值myFunction
-
myFunction
返回一个函数(调用alert
)
这意味着每秒都会发出警报。
也可以看看为什么函数语句需要名称?
* Or a string to be evaluated, but a reference is preferred.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)