Implicit call of valueOf and toString in JavaScript

Source: Internet
Author: User

Implicit call of valueOf and toString in JavaScript

Someone asked this question in the group today:

Function add can implement continuous addition operations
The function add syntax is as follows:
Add (num1) (num2) (num3)...; // note that the ellipsis (...) is infinite.
Example:
Add (10) (10) = 20;
Add (10) (20) (50) = 80;
Add (10) (20) (50) (100) = 180;
Use js Code to implement function add.

After thinking about it for a while, you can only Google it. The Code is as follows:

 
 
  1. function add(num){ 
  2.         var sum=num, 
  3.          
  4.             tmp=function(v){ 
  5.                 sum+=v; 
  6.                 return tmp 
  7.             }; 
  8.          
  9.         tmp.toString=function(){ 
  10.             return sum 
  11.         }; 
  12.          
  13.         return tmp 
  14.     } 
  15.      
  16.      
  17.     alert( add(10)(20)(50) )        //80 

I didn't understand why the toString method returned 80 at first, because the toString method has never been called. How can I return sum? Later I learned that the toString method was called implicitly, so I can see the following.

Here is a reference:

The toString and valueOf methods of each object can be rewritten. After each object is executed, if it is used to operate the JavaScript parser, The toString or valueOf method of the object will be automatically called. For example:

 
 
  1. // Create an object and modify its toString and valueOf methods.
  2. Var obj = {
  3. I: 10,
  4. ValueOf: function (){
  5. Console. log ('executed valueOf ()');
  6. Return this. I + 20
  7. },
  8. ToString: function (){
  9. Console. log ('executed toString ()');
  10. Return this. valueOf () + 20
  11. }
  12. }
  13. // When we call:
  14. Alert (obj) // 50 executes toString () and valueOf ()
  15. Alert (+ obj) // 30 executes valueOf ()
  16. Alert (obj> 40) // false: valueOf () is executed ()
  17. Alert (obj = 30) // true executes valueOf ()
  18. Alert (obj = 30) // false
  19. // At last, no string is output. I guess this is the case. During full comparison, the js parser directly checks whether the types are the same. Obviously, one is Object and the other is Number, therefore, they do not need to be evaluated.

It can be seen from the above that although we have not called any method of obj, it seems that when we want to use obj for operations, if we are the person who creates the js parser, this is not a problem, AH) The js parser automatically helps us call its toString or valueOf method.

The next step is to explore when the toString method is executed and when the valueOf method is executed. In general, if the valueOf method is executed during addition, subtraction, multiplication, division, and comparison, and if the specific value is required, the toString method is executed. For more rigorous lab copying, please forgive the original article address ):

Here, we will review the previous usageAddition and subtraction of strings and numbersImplicit conversions of other operations:

 
 
  1. var age = 30; 
  2. age.toString() + 'year old'; // '30 year old' 
  3. age + ' years old'; // '30 years old' 

When age. toString () + 'year old' is run, the age variable is converted from Number to String by calling the toString function. When we run age + 'years old', we did not explicitly call the function, and age was converted to the String type. Here, the javascript engine has implicitly converted the type. Implicit type conversion can be considered as a type conversion function called by the javascript engine. age + 'ears old' is actually equivalent to age. toString () + 'years old', implicit type conversion and explicit type conversion are actually the same thing, of course, specifically, how can we do implicit conversions? The person who made the js parser knows the most clearly. Why didn't he tell us how to create it... (☆☆ )... is such a game fun ).
Haha, actually, I didn't do any in-depth research on implicit type conversion. I only know, oh, yes, it's implicit type conversion. So I don't know what's going on in the form of the add function above, but now it's clear ).

Refer:

Http://www.cnblogs.com/rubylouvre/archive/2010/10/01/1839748.html

Http://zjuwwq.gitbooks.io/jump_javascript/content/data_types/type_conversion.html

Related Article

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.