JavaScript中的回调函数语法

huangapple go评论54阅读模式
英文:

Callback function syntax in Javascirpt

问题

这段代码做什么?为什么我们要像这样编写y函数,而不是像这样编写。

英文:

Guys i am a newbie in Javascript and i really need your help.

const f = ()=>{
    
}

const y = f(()=>{

})

What does this code do ? Why we write y function this way instead of doing like this.

const y = f()=>{

}

答案1

得分: 2

const y = f(()=>{}) 将一个箭头函数作为函数 f 的第一个参数传递,并将 f 的返回值存储在变量 y 中。将函数传递给其他函数通常用于回调。

英文:

const y = f(()=>{}) passes an arrow function as the first argument to the function f and stores the return value of f in the variable y. Passing functions to other functions is commonly used for callbacks.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const f = arg =&gt; {
  console.log(&#39;first argument to f&#39;, arg);
  return &quot;return value&quot;;
}
const y = f(()=&gt;{});
console.log(y);

<!-- end snippet -->

答案2

得分: 0

以下代码是无效的。所以你不能写出这样的一个函数

const y = f() => {

}

这段代码const y = f(() => {})之所以这样写是因为f是一个函数,因此使用了f()。你正在调用f,并将匿名函数作为第一个参数传递。f将对该函数进行某些操作,就像对其他函数参数一样。

这被称为将“回调”作为参数传递。你可以在这里阅读更多。

MDN的示例:

function greeting(name) {
  alert(`Hello, ${name}`);
}

// 这将是你的`f`函数
function processUserInput(callback) {
  const name = prompt("请输入您的姓名。");
  callback(name);
}

processUserInput(greeting);

代码const f = () => {}是一个名为f的普通函数。

英文:

The following code is invalid. So you cannot write a function like that

const y = f()=&gt;{

}

The reason the code const y = f(()=&gt;{}) is written like that is because f is a function, hence the f(). You're calling f with the first argument being an anonymous function. f will do something with that function, as with any other function argument.

That's called passing a "callback" as an argument. You can read more here

The example from MDN:

function greeting(name) {
  alert(`Hello, ${name}`);
}

// this would be your `f` function
function processUserInput(callback) {
  const name = prompt(&quot;Please enter your name.&quot;);
  callback(name);
}

processUserInput(greeting);

The code const f = ()=&gt;{} is a normal function called f.

huangapple
  • 本文由 发表于 2023年2月8日 23:09:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定