Understanding of valueOf and toString in JavaScript Functions, valueoftostring

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.