Understanding of valueOf and toString in JavaScript Functions, valueoftostring
I saw a question today and implemented the following syntax functions:
var a = add(2)(3)(4); //9
This is an application of a higher-order function. Analysis: add (2) returns a function, add (2) (3) returns a function, and add (2) (3) (4) return a value.
Implementation:
function add(num1){return function(num2){return function(num3){return num1+num2+num3;}}}add(2)(3)(4);//9
This is a perfect solution.
Optimization: here we will only discuss about the higher-order functions. For better solutions, we can implement unlimited calls,
// 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 elegant method (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, 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 have never understood in [url = functions, and I also tried to output [code = javascript, javascript code, true] function 9 on the console.
var temp = function() {}temp.valueOf = function() {return 2;}temp.toString = function() {return 'hahh';}alert(temp);console.log(2 * temp);
To convert to a string, toString is called. to convert to a number, valueOf is called.