簡體   English   中英

立即調用的函數表達式(iife)如何作為setTimeout的參數工作

[英]How immediately invoked function expression (iife) work as an argument to setTimeout

誰能幫我理解為什么執行返回的函數?

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 ms之后執行。

我建議您以其他方式執行此操作:

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);
}

學到更多:

因為它是IIFE

有一個稱為IIFE或立即調用的函數表達式的東西,它們以以下方式工作(立即調用的函數表達式)

(function(received argument){

     //some code here.......

})(passed argument)  //<-- here the function is invoked immediately after creation

上面的函數在創建時立即被調用。 這種類型的聲明用於使變量保持私有並保持全局名稱空間整潔。

相當於

function f(){} // we declare the function first

f() // and we invoked it later

代碼中的模式用於創建模塊

在您的情況下:

setTimeout接受一個函數作為它的第一個參數。您使用了IIFE,它將立即調用並返回一個函數。此返回的函數用作setTimeout中的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM