Understanding of valueOf and toString in the JavaScript function

  • 2021-06-28 10:38:38
  • OfStack

Today I see a test to achieve the following grammatical functions:


var a = add(2)(3)(4); //9 

This is the application of a higher-order function: add(2) returns a function, add(2) (3) returns a function, and add(2) (3) (4) returns a numeric value.

Realization:


function add(num1){
return function(num2){
return function(num3){
return num1+num2+num3;
}
}
}
add(2)(3)(4);//9 

This is correct, it will solve the problem perfectly.

Optimize: Only the higher-order functions are discussed here, and for better solutions, infinite calls can be made.


// 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.  See also 1 A 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 Note: Actually it is equivalent to , Only custom attributes are applied to the function to store values. 
;(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 [url=http://www.cnblogs.com/wengxuesong/p/5577683.html] Blog Park [/url]. I didn't understand method 1 and method 21 and tried to output [code=javascript, javascript code, true] function 9 from the console.


var temp = function() {
}
temp.valueOf = function() {
return 2;
}
temp.toString = function() {
return 'hahh';
}
alert(temp);
console.log(2 * temp); 

toString is called when converting to a string and valueOf is called when converting to a number.


Related articles: