據說回調通過將回調函數的值(其函數定義)傳遞給“高階”函數的參數,在該參數中傳入并執行,從而為高階函數添加功能。似乎我們可以通過從另一個執行函數內部調用外部函數來完成同樣的事情。以下內容更好地說明了我想說的內容。// ************************ 使用回調 ************************ ****************************function A() { // this is the callback function return 'hello';};function B(callback) { // this is considered a 'higher-order' function because it takes a // function definition as a parameter. the function definition of A // -- taken from A in Global memory -- is assigned to callback var output = callback(); // we call callback and run it // the value of callback, is assigned to the variable output console.log(output); console.log("goodbye")};B(A); // logs 'hello' 'goodbye'// ******* 將上述與從另一個函數內部調用外部函數進行比較 *****function A() { return 'hello';};function B() { var output = A(); // we call function A, from inside function B, // the value returned by A, is assigned to a variable inside B console.log(output); console.log("goodbye")};B(); // logs 'hello' 'goodbye'雖然兩者在返回值方面沒有區別,但它們的執行方式卻有所不同?;卣{函數接受 A 的函數定義并將其附加到一個名為回調的新名稱?;卣{被執行,并在回調的本地執行上下文中運行。將此與從 B 內部調用 A 時發生的情況進行比較,A 在其自己的本地執行上下文中執行。也許這個例子太簡單了,看不出這兩個之間的差異會幫助我理解什么時候使用一個而不是另一個。
執行外部函數 Vs。使用回調函數——何時使用其中一個?
忽然笑
2021-11-25 19:40:00