請忽略這樣的事實,即這段代碼什麼都不做,並且對可能是一個瘋狂的問題表示歉意!爲什麼我不能將函數調用(而不是函數引用或匿名函數)傳遞給setTimeout()?
據我所知,我不能通過函數調用setTimeout()
作爲第一個參數,但爲什麼我不能這樣做?
let names = ['Andy', 'Ross', 'David'];
function printer (name) {
console.log(name);
}
names.forEach(name => setTimeout(printer(name), 1000);
結果:
Andy
timers.js:327
throw new TypeError('"callback" argument must be a function');
^
我可以解決,而不是使用參考printer
使用bind()
送與它一起name
的問題,但我爲什麼一定要把這些額外的步驟?
let names = ['Andy', 'Ross', 'David'];
function printer (name) {
console.log(name);
}
names.forEach(name => setTimeout(printer.bind(null, name), 1000));
結果:
Andy
Ross
David
因爲setTimeout應該會收到一個應該稍後調用的回調 –