Sometimes, we want to clone a function with JavaScript.
In this article, we’ll look at how to clone a function with JavaScript.
How to clone a function with JavaScript?
To clone a function with JavaScript, we can create a new function that calls the original function with the same arguments.
For instance, we write
const oldFunction = (params) => {
// ...
};
const clonedFunction = (...args) => oldFunction(...args);
to create the oldFunction
function.
Then we make a clone of that by defining the clonedFunction
function that takes an unlimited number of arguments and calls oldFunction
with all the arguments.
We use ...
in the parameter to get the arguments into the args
array.
And then we use ...
in the oldFunction
to spread the args
array entries as arguments.
Conclusion
To clone a function with JavaScript, we can create a new function that calls the original function with the same arguments.