繁体   English   中英

将 function 转换为箭头 function

[英]Convert function to arrow function

我正在尝试将 function 转换为箭头 function 但它不起作用。 我做错了我的代码如下。 请指导我在哪里做错了。

// 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)

你有一个大括号迟到了。

一种更短的方法是使用带有条件语句的函数。

 const ask = (question, yes, no) => (confirm(question)? yes: no)(), showOk = () => console.log("you agreed"), showCancel = () => console.log("Canceled"); ask("do you agree?", showOk, showCancel);

它可能会抛出 ReferenceError,因为 showOk 和 showCancel 是在箭头 function 的 scope 中声明的,而不是全局声明的。

对于箭头 function 需要有一个隐式返回表达式,所以对于每个 function,你必须返回一些东西,如果你使用 {},至少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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM