Puzzle: JS Function that returns itself until there are no arguments

后端 未结 5 2066
北荒
北荒 2020-12-06 14:29

I\'m trying to solve a puzzle, and am at my wit\'s end trying to figure it out.

I\'m supposed to make a function that works like this:

add(1);                


        
5条回答
  •  长情又很酷
    2020-12-06 14:50

    To answer "how dow this work". Given:

    function add(n) {
        function calc(x) {
            return add(n + x);
        }
        calc.valueOf = function() {
            return n;   
        }
        return calc;
    }
    
    var sum = add(1)(2)(3); // 6
    

    When add is called the first time, it stores the value passed in in a variable called n. It then returns the function calc, which has a closure to n and a special valueOf method (explained later).

    This function is then called with a value of 2, so it calls add with the sum of n + x, wich is 1 + 2 which 3.

    So a new version of calc is returned, this time with a closure to n with a value of 3.

    This new calc is called with a value of 3, so it calls add with n + x, which this time is 3 + 3 which is 6

    Again add returns a new calc with n set to 6. This last time, calc isn't called again. The returned value is assigned to the variable sum. All of the calc functions have a special valueOf method that replaces the standard one provided by Object.prototype. Normally valueOf would just return the function object, but in this case it will return the value of n.

    Now sum can be used in expressions, and if its valueOf method is called it will return 6 (i.e. the value of n held in a closure).

    This seems pretty cool, and sum will act a lot like a primitve number, but it's actually a function:

    typeof sum == 'function';
    

    So be careful with being strict about testing the type of things:

    sum * 2   // 12
    sum == 6  // true
    
    sum === 6 // false -- oops!!
    

提交回复
热议问题