Home > Web Front-end > JS Tutorial > How to Pass Extra Arguments to a Callback Function?

How to Pass Extra Arguments to a Callback Function?

Mary-Kate Olsen
Release: 2024-12-07 16:02:15
Original
503 people have browsed it

How to Pass Extra Arguments to a Callback Function?

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);
};
Copy after login

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);
});
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template