Passing an Additional Argument to a Callback Function
In some scenarios, it may be necessary to pass an extra argument to a callback function. This can be achieved through a simple wrapping function or arrow function.
Consider the following example:
const callWithMagic = callback => { const magic = getMagic(); callback(magic); };
Here, the callWithMagic function takes a callback function as a parameter and calls it with one argument. Suppose you have another function, processMagic, that requires two arguments: magic and theAnswer.
To pass processMagic as an argument to callWithMagic and provide an additional argument (42) to processMagic, you can create a wrapper function:
callWithMagic(function(magic) { return processMagic(magic, 42); });
Alternatively, using ECMAScript 6 arrow functions, you can write:
callWithMagic(magic => processMagic(magic, 42));
Both of these approaches allow you to pass the extra argument to the processMagic function while still adhering to the signature expected by callWithMagic.
The above is the detailed content of How Can I Pass an Additional Argument to a Callback Function?. For more information, please follow other related articles on the PHP Chinese website!