curry - classic face questions

function the Add () {
     // the first execution, definition of an array designed to store all parameters 
    var _args = Array.prototype.slice.call (arguments); 

    // declared inside a function, properties of closures _args save all parameter values collected and 
    var _adder = function () { 
        _args.push (... arguments); 
        return _adder; 
    }; 

    // use implicit conversion characteristic toString, when implicit conversion performed last, and calculate the final value is returned 
    _adder.toString = function () {
         return _args.reduce ( function (a, B) {
             return a + B; 
        }); 
    } 
    return _adder; 
}

Look at the function call

add(1)(2)(3); //6
add(1)(2)(3)(4); //10

The reason: js is a weakly typed language,

such as:

There are a = 1 + '0'; // a == '10' 
has b = 1 - '1'; // b == '0' 
has C = (1 == '1'); // c == true

The above are some implicit conversion, such as the back of a field converted to a string an integer '1'.

Similarly objects (functions are also objects) will be a case of hidden conversion.

such as:

var obj = {}

var ret = obj + '1' // [object Object]1

Here the object is implicit conversion time will call toString this method, you can override this method if the proxy method

Back to the interview questions, add method returns _adder actually returned _adder.toString () results, so the toString () after rewriting, you can use this method implicitly calls _adder.toString.

 

Guess you like

Origin www.cnblogs.com/hellolol/p/11086691.html