To achieve a similar add (1) (2) (3) effects result 6

    Two days ago to see to a question how to achieve the add method to achieve add (1) (2) (3) as a result of 6, began sparked my thinking.

 1. To achieve the add () () calls this way, the return value of add () method is a function must be 

function the Add () {
         var TEMP = function () {
               return TEMP; // needs to support multiple calls, temp needs to return itself           
        }
         return TEMP; 
}

   2. Design Parameters

function add(x){
        var sum = x;    
        var temp = function(y){
                sum += y;
                return temp;
        }
        return temp;
}

3. Step two returned after the implementation of add (1) is a function, how to let him return to the accumulated value out of it? Here we must use black & toString valueOf method or methods, the original in the above methods return temp temp time will try to call temp.toString or temp.valueOf method, so we rewrite toString and valueOf method returns the sum in the process value.

function add(x){
            var sum=x;
            function temp(y){
                sum+=y;
                return temp;
            }
            temp.toString=function(){
                 return sum;
            }
            return temp;
}
add(1)(2)(3);//f 6 
typeof add(1)(2)(3) //function
add(1)(2)(3) == 6 //true
add(1)(2)(3) === 6; //false

Note that add (1) (2) (3) The result type is actually a function of the value to be used or actually used '+' turn about. + Add (1) (2) (3) The result is orthodox type number 6 friends

ToString priority issue and valueOf: the object as an operand, the interpreter calls the priority always valueOf () - (Object type Date binary "+" when the operation exception), and other cases, the total interpreters we want to believe that is a string, it will take precedence call toString (), the above situation is the situation toString priority calls, so if the above is not just rewrite valueOf perform self valueOf method defined (will not rewrite toString calls on the prototype)

Question: There are ways to achieve add (1) (2) (3) === 6 it?

 

Guess you like

Origin www.cnblogs.com/luoyanan/p/11820183.html