簡體   English   中英

如何使用箭頭 function 編寫此回調代碼?

[英]How to write this callback code using arrow function?

JavaScript 和箭頭 function 的初學者。

我嘗試將以下語法更改為箭頭 function 格式但失敗了。

正常 function:

function add(a, b, callback) {
    document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`);
    callback();
}

function secondLine(){
document.write("The callback must be printed after addition.");
}

add(1,2,secondLine)

箭頭 function

((a, b, callback) => {
document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`);
callback();
})

(secondLine() => {
document.write("The callback must be printed after addition.");
})

(1,2,secondLine)

控制台只返回

The sum of function(){document.write("The callback must be printed after addition.");} and undefined is function(){document.write("The callback must be printed after addition.");}undefined.

我不應該在回調中使用箭頭 function 嗎? 如果我真的想使用回調,應該如何輸入語法?

提前謝謝了。

您可以嘗試以下方法:

 (function(){ var add = (a, b, callback) => { document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`); callback(); } var secondLine = () => { document.write("The callback must be printed after addition."); } add(1,2,secondLine); })();

您的原始代碼沒有任何問題,不使用箭頭函數真的很好。 addsecondLine聲明為變量允許進行任意數量的類似調用,例如add(3,7,secondLine)add(42,0,secondLine)

如果您不想重用secondLine (即您只需要它作為該單個調用的參數),您可以將其轉換為未命名的 function 表達式,並將其寫在參數的位置:

add(1, 2, function() {
    document.write("The callback must be printed after addition.");
});

您現在可以輕松地將其更改為箭頭 function:

add(1, 2, () => {
    document.write("The callback must be printed after addition.");
});

暫無
暫無

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

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