将一个额外的参数传递给回调函数 [英] 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?>);
推荐答案
只需创建一个包装回调:
Just create a wrapper callback:
callWithMagic(function(magic) {
return processMagic(magic, 42);
});
或者使用ECMAScript 6 arrow functions :
Or using ECMAScript 6 arrow functions:
callWithMagic(magic => processMagic(magic, 42));
这篇关于将一个额外的参数传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文