How to Pass an Additional Argument to a Callback Function
When working with callback functions, it may arise to pass additional arguments than those expected by the callback function. Here's how to achieve this:
Consider a function callWithMagic that accepts a callback and invokes it with a single argument:
const callWithMagic = callback => { const magic = getMagic(); callback(magic); };
If you have a function processMagic that requires two arguments (magic and theAnswer), you can pass it to callWithMagic by creating a wrapper callback function:
callWithMagic(function(magic) { return processMagic(magic, 42); });
This wrapper function accepts the required magic argument and passes it along with the additional argument 42 to processMagic.
Alternatively, if your environment supports ECMAScript 6, you can leverage arrow functions:
callWithMagic(magic => processMagic(magic, 42));
This concise syntax effectively assigns the callback logic to a function that directly invokes processMagic with the additional argument.
The above is the detailed content of How to Pass Extra Arguments to a Callback Function?. For more information, please follow other related articles on the PHP Chinese website!