The function is currified

What is a function Coriolization?

Currying, English: Currying, is a technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the remaining arguments and returns a result.

Implement the function Currize

//add(1)(2)(3)
function add(a){
	return function(b){
		a = a + b; 
		return function(c){
			a = a + c;
			returna; }}}Copy the code
// Implement an add method that satisfies the following expectations:
add(1) (2) (3) = 6;
add(1.2.3) (4) = 10;
add(1) (2) (3) (4) (5) = 15;

function add(){
    // On the first execution, an array is defined to store all the parameters
    var _args=Array.prototype.slice.call(arguments)
    // Internally declare a function that uses closure properties to hold _args and collect all parameter values
    var _adder = function(){ _args.push(... arguments)return _adder
    }
    // The toString stealth conversion feature
    _adder.toString = function(){
        return _args.reduce(function(a,b){
            return a+b
        },0)}return _adder;
}
Copy the code

Rewrote the toString() method of _adder so that the _adder function could be printed as number.

Array. The prototype. Slice. The call (the arguments), rounding

Array. Prototype. Slice. The call () can be understood as: change scope Array slice method, in certain scope to call slice method, call () method of the second parameter passed to the parameters of the slice that capture the starting position of the Array.

Array. Prototype. Slice. The call (the arguments) will have the length attribute object into an Array, in addition to the IE node set (IE the dom object is implemented in the form of com objects, js object with the com object can’t transform). Arguments.toarray ().slice().

  • The slice() method returns selected elements from an existing array.
  • The call () and apply () methods call a function in a specific scope, essentially setting the value of this object in the function body. The first argument to the apply and Call methods is scope-specific. In contrast, the second argument to apply can be an instance of Array or arguments object. The call method needs to list the parameters to be passed individually.