The method of curry is to transform a function that accepts multiple parameters into a function that takes a single parameter, and returns a new function that accepts the parameters of the original function. Here are some examples to help you understand.
function adder (num) {
return function (x) {
return num + x;
}
}
var add5 = adder (5);
var add6 = adder (6);
Print (ADD5 (1)); 6
Print (ADD6 (1)); 7
The function adder takes a parameter and returns a function that returns a function that can be called as expected. The variable add5 holds the function returned by the adder (5), which can accept a parameter and return the and of the argument to 5. Currying is useful in the DOM callback.
The main function of the function curry is to provide a powerful method for creating dynamic functions, which is obtained by invoking another function and passing it the function and necessary parameters to be currying. The popular point is to use the existing functions, and then create a dynamic function, the dynamic function inside or through the existing functions to take effect, just pass in more parameters to simplify the function of the parameters of the call.
Function Curry (FN) {
var args = [].slice.call (arguments, 1);
return function () {
return fn.apply (NULL, Args.concat ([].slice.call (arguments, 0)));
}
}
function Add (NUM1, num2) {
return NUM1 + num2;
}
var newadd = Curry (add, 5);
Alert (Newadd (6)); 11
Inside the curry function, the private variable args is equivalent to a memory that is used to temporarily store the value of the parameter passed when the curry function is called, so that it is merged and executed with the arguments that are created when the function is called dynamically, and the same effect is obtained.
The basic method of the function curry is the same as the function binding: Returns a function with a closure. The difference between the two is that when a function is called, the return function also needs to set some incoming arguments.
function bind (FN, context) {
var args = Array.prototype.slice.call (arguments, 2);
return function () {
var Innerargs = Array.prototype.slice.call (arguments);
var Finalargs = Args.concat (Innerargs);
Return fn.apply (context, Finalargs);
};
}
The common way to create a curry function is:
Function Curry (FN) {
var args = Array.prototype.slice.call (arguments, 1);
return function () {
var Innerargs = Array.prototype.slice.call (arguments);
var Finalargs = Args.concat (Innerargs); Retrun
Fn.apply (null, Finalargs);
};
}
The main function of the curry function is to sort the parameters of the returned function. To get all parameters after the first argument, call the slice () method on the arguments object and pass in Parameter 1, which indicates that the first element of the returned array should be the second argument.
This article: Copy from http://book.2cto.com/201211/9320.html;
Writing high-quality code: 188 Tips for improving JavaScript programs
Recommendation 75: Function currying