如何使用箭头函数编写此回调代码?
How to write this callback code using arrow function?
JavaScript 的初学者和此处的箭头函数。
我尝试将以下语法更改为箭头函数格式但失败了。
正常功能:
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)
箭头函数
((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)
仅限控制台 returns
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.
我不应该在回调中使用箭头函数吗?如果真的要用callback,语法应该怎么打?
非常感谢。
您可以尝试以下方式:
(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);
})();
你原来的代码没有问题,不使用箭头函数真的很好。将 add
和 secondLine
声明为变量允许进行任意数量的类似调用,例如 add(3,7,secondLine)
和 add(42,0,secondLine)
.
如果你不想重复使用 secondLine
(即你只需要它作为那个单一调用的参数),你可以将它转换成一个未命名的函数表达式,然后把它写在正确的地方参数:
add(1, 2, function() {
document.write("The callback must be printed after addition.");
});
你现在可以很容易地把它变成一个箭头函数:
add(1, 2, () => {
document.write("The callback must be printed after addition.");
});
JavaScript 的初学者和此处的箭头函数。
我尝试将以下语法更改为箭头函数格式但失败了。
正常功能:
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)
箭头函数
((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)
仅限控制台 returns
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.
我不应该在回调中使用箭头函数吗?如果真的要用callback,语法应该怎么打?
非常感谢。
您可以尝试以下方式:
(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);
})();
你原来的代码没有问题,不使用箭头函数真的很好。将 add
和 secondLine
声明为变量允许进行任意数量的类似调用,例如 add(3,7,secondLine)
和 add(42,0,secondLine)
.
如果你不想重复使用 secondLine
(即你只需要它作为那个单一调用的参数),你可以将它转换成一个未命名的函数表达式,然后把它写在正确的地方参数:
add(1, 2, function() {
document.write("The callback must be printed after addition.");
});
你现在可以很容易地把它变成一个箭头函数:
add(1, 2, () => {
document.write("The callback must be printed after addition.");
});