Categories
JavaScript Answers

How to bind function arguments without binding this with JavaScript?

Spread the love

Sometimes, we want to bind function arguments without binding this with JavaScript.

In this article, we’ll look at how to bind function arguments without binding this with JavaScript.

How to bind function arguments without binding this with JavaScript?

To bind function arguments without binding this with JavaScript, we return a function that calls the function that we want to bind the arguments with.

For instance, we write

const bindArgs = (func, ...boundArgs) => {
  return (...args) => {
    return func(...boundArgs, ...args);
  };
};

const deleteGroup = bindArgs(deleteGroup, "groupName1");

to create the bindArgs function that returns a function that calls func with the arguments from the boundArgs array and the args that we pass into the function returned by bindArgs.

Then we call bindArgs with the deleteGroup and args being an array with 'groupName1'.

Conclusion

To bind function arguments without binding this with JavaScript, we return a function that calls the function that we want to bind the arguments with.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *