我正在尝试将功能转换为箭头功能,但是它不起作用。我在做一些错误吗,我的代码在下面。请引导我在哪里做错。
// Call Back Function
function ask(question, yes, no) {
if (confirm(question)){
yes()
} else {
no()
}
}
function showOk() {
console.log("you agreed")
}
function showCancel() {
console.log("canceled")
}
ask("do you agree ?", showOk, showCancel)
// Arrow Function
let ask = (question, yes, no) => {
if (confirm(question)) {
yes()
} else {
no()
}
let showOk = () => console.log("you agreed");
let showCancel = () => console.log("Canceled");
}
ask("do you agree ?", showOk, showCancel)
答案 0 :(得分:0)
您要大括号了。
一种较短的方法是将这些函数与条件语句一起使用。
const
ask = (question, yes, no) => (confirm(question) ? yes : no)(),
showOk = () => console.log("you agreed"),
showCancel = () => console.log("Canceled");
ask("do you agree ?", showOk, showCancel);
答案 1 :(得分:0)
可能会引发ReferenceError,因为showOk和showCancel是在箭头函数的范围内而不是在全局范围内声明的。
答案 2 :(得分:-1)
要使箭头函数具有隐式返回表达式,
因此对于每个函数,您都必须返回一些值,如果使用{},则至少要返回return true
。
您的代码应类似于
let ask = (question, yes, no) => {
if (confirm(question)) {
return yes();
}
return no();
}
let showOk = () => {
console.log("you agreed");
return true;
};
let showCancel = () => {
console.log("Canceled");
return true;
};
ask("do you agree ?", showOk, showCancel);