英文:
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 => {
console.log('first argument to f', arg);
return "return value";
}
const y = f(()=>{});
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()=>{
}
The reason the code const y = f(()=>{})
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("Please enter your name.");
callback(name);
}
processUserInput(greeting);
The code const f = ()=>{}
is a normal function called f
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论