将额外的参数传递给回调函数 [英] Pass an extra argument to a callback function
本文介绍了将额外的参数传递给回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数 callWithMagic
,它接受一个回调函数作为参数并用一个参数调用它.
I have a function callWithMagic
which takes a callback function as a parameter and calls it with one argument.
const callWithMagic = callback => {
const magic = getMagic();
callback(magic);
};
我还有一个函数 processMagic
,它接受两个参数:magic
和 theAnswer
.
I also have a function processMagic
which takes two arguments: magic
and theAnswer
.
const processMagic = (magic, theAnswer) => {
someOtherMagic();
};
我想将函数 processMagic
作为参数传递给 callWithMagic
,但我也想将 42
作为第二个参数传递(theAnswer
) 到 processMagic
.我该怎么做?
I want to pass the function processMagic
as an argument to callWithMagic
, but I also want to pass 42
as the second parameter (theAnswer
) to processMagic
. How can I do that?
callWithMagic(<what should I put here?>);
推荐答案
只需创建一个 function(magic) {}
作为包装回调:
Just create a function(magic) {}
as a wrapper callback:
callWithMagic(function(magic) {
return processMagic(magic, 42);
});
或者使用ECMAScript 6:箭头函数:
callWithMagic(magic => processMagic(magic, 42));
这篇关于将额外的参数传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文