繁体   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