谁能帮我理解为什么返回的函数会被执行?
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function(i_local) {
//The function below is just returned and not called using '()', so why is it executed? Why does the console.log works?
return function() {
console.log('The index of this number is: ' + i_local);
}
}(i), 3000);
}
最佳答案
setTimeout
函数获取一个函数作为参数,并在 X 毫秒后执行它。
在 JavaScript 中,函数就像任何其他变量一样。您可以将它们作为参数传递给其他函数。其他函数可以稍后执行。
像这样:
function setNow(func){
func()
}
setNow(function(){
console.log('this will be executed.')
})
同样,即使您不使用 ()
直接调用该函数,该函数也会被执行。
在您的示例中,您的内部函数返回,现在这是 setTimeout
接收的函数。它将在 X 毫秒后执行。
我建议您以不同的方式进行操作:
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout( (i_local=> {
console.log('The index of this number is: ' + i_local);
}).bind(this,i), 3000);
}
了解更多:
关于javascript - 立即调用的函数表达式 (iife) 如何作为 setTimeout 的参数工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252525/