Function currying understand notes

In Detailed JS function currying seen such an example to help you understand currying execution logic, I'm a little comb.

. 1  function the Add () {
 2      // first execution, definition of an array designed to store all the parameters 
. 3      var _args = Array.prototype.slice.call (arguments);
 . 4  
. 5      // inside a function declaration, closure usage characteristics stored _args and collect all parameter values 
. 6      var _adder = function () {
 . 7          _args.push (... arguments);
 . 8          return _adder;
 . 9      };
 10  
. 11      // use implicit conversions toString feature, when an implicit conversion performed last, and calculates the final value of the return 
12 is      _adder.toString = function () {
 13 is          return _args.reduce ( function (a, b) {
14             return a + b;
15         });
16     }
17     return _adder;
18 }
19 
20 console.log(add(1)(2)(3).toString());

 add (1) (2) ( 3) .toString () to perform  the Add (. 1) , this time code may be considered to have become  _adder (2) (. 3) .toString () , while there is only one variable _args 1. Then begin  _adder (2) , _adder function before it has been successfully assigned the following method:

var _adder = function() {
   _args.push(...arguments);
   return _adder;
};

By this method, constantly passing new parameters to _args, and finally achieve the purpose of summary of all variables.

.toString overridden method, all variables are added, the final output.

Overall it, the main advantage of currying function is looking very nice, very provincial code. But it is closure, but also .call, performance is certainly not as simple logic. But how much difference a matter of personal feeling, in fact, is basically imperceptible. Used or not, or to measure the project according to the situation.

Guess you like

Origin www.cnblogs.com/tinyTea/p/11105312.html