Today I saw a test question that implements the following grammar functions:
var a = add(2)(3)(4); //9
This is the application of a higher-order function. Analysis: add(2) will return a function, add(2)(3) will also return a function, and finally add(2)(3)(4) will return a numeric value.
accomplish:
function add(num1){return function(num2){return function(num3){return num1+num2+num3;}}}add(2)(3)(4);//9There is nothing wrong with this, it can solve the problem perfectly.
Optimization: Only the part about higher-order functions is discussed here. For better solutions, infinite calls can be implemented.
//Method 1 function add(a) {var temp = function(b) {return add(a + b);}temp.valueOf = temp.toString = function() {return a;};return temp;}add(2)(3)(4)(5);//14//Method 2. Another very elegant way of writing (from Gaubee): function add(num){num += ~~add;add.num = num;return add;}add.valueOf = add.toString = function(){return add.num};var a= add(3)(4)(5)(6); // 18//Method 2 comment: In fact, it is equivalent to, but a custom attribute is applied to the function to store the value. ;(function(){var sum=0;function add(num){sum+=num;return add;}add.valueOf=add.toString=function(){return sum;}window.add=add;})()var a= add(3)(4)(5)(6); // 18[/code]This is what I wrote in the article I saw in [url=http://www.cnblogs.com/wengxuesong/p/5577683.html]Blog Garden[/url]. I have never understood the method one and method two, and I also tried to output the [code=javascript,javascript code, true]function 9 in the console
var temp = function() {}temp.valueOf = function() {return 2;}temp.toString = function() {return 'hahh';}alert(temp);console.log(2 * temp);When it needs to be converted to a string, toString will be called, and valueOf will be called when it needs to be converted to a number.