詳解回調函數(小白也能看得懂的)

A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.

Maybe a better name would be a "call after" function.

This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.

A callback function is a function which is:

  • accessible by another function, and
  • is invoked after the first function if that first function completes

按照 MDN 的描述:回調函數是作爲參數傳給另一個函數的函數,然後通過在外部函數內部調用該回調函數以完成某種操作

讓我用人話解釋一下,回調函數是一個函數,將會在另一個函數完成執行後立即執行。回調函數是一個作爲參數傳給另一個 JavaScript 函數的函數。這個回調函數會在傳給的函數內部執行。

在 JavaScript 中函數被看作是一類對象。對於一類對象,我們的意思是指數字、函數或變量可以與語言中的其他實體相同。作爲一類對象,可以將函數作爲變量傳給其他函數,也可以從其他函數中返回這些函數。

例如:

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('請輸入你的名字。');
  callback(name);
}

processUserInput(greeting);

以上範例爲 同步 回調,它是立即執行的。

然而需要注意的是,回調函數經常被用於繼續執行一個異步 完成後的操作,它們被稱爲異步回調。

另一個例子:

// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
function printANumber(number, callbackFunction) {
    console.log("The number you provided is: " + number);
    setTimeout(function() { callbackFunction(); }, 3000); 
    console.log("second");
}
 
// a function which we will use in a driver function as a callback function
function printFinishMessage() {
    console.log("I have finished printing numbers.");
}
 
// Driver method

printANumber(6, printFinishMessage);

執行printANumber函數後,結果:

> "The number you provided is: 6"
> "second"
> "I have finished printing numbers."

The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.

Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.

Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章