The ToString () and valueof () method of Object

Source: Internet
Author: User
Tags numeric value

Deep understanding of ToString () and valueof () functions

1. Why do we have to understand both of these methods

It is well known that the toString () function and the valueof function, which are objects of the object class, are inherently owned, and they allow us to rewrite them, so what is the use of these two functions?

Judging from the name, toString () converts the object to a string, valueof the object to a value. So the question is: when do I need to convert an object to a value, and when do I need to convert the object to a string? ------This is the core of our article.

Before we talk about this question, let's look at a topic:

This is a very classic topic, the investigation is our understanding of some basic concepts, of course, is also a difficult topic, even at first glance seems to be an impossible problem.  1 Please implement in JavaScript language, var a= add (1) (2) (3) (4) (5); The result is a sum of 5 numbers,------------from


.. The above topic is not so easy to think about, and in general, programmers do not write the code that they look awkward. We only use this to derive some of the most basic concepts, but also the necessity of the existence of this article.

From the example above, we can see that the conversion between the function type and the string type is associated with the output. So, how does this transition happen? In the second part, you will be given a satisfactory explanation.

Now we need to know one thing: ToString and valueof are two functions that the interpreter uses to help us automate the transformation between types (typically objects to basic types), and then output results that are satisfying.

2. Rules for conversion of objects to basic data types

(1) vauleof precedence over ToString () is invoked---------when an object is an operand (except for date type)

Let's take a look at the following operation, the conversion of the data type

1 var x= "ten";
 3 var a=+x;
 4 Console.log (typeof a);     
 7 var b=a+x;
 8 Console.log (typeof b);    
var object={};
One object[a]=10000;
Console.log (object[10]);  
Output results

It's just three of the more common type conversions I've enumerated, and some of the most basic concepts ... Let's take a moment to parse how these three types of conversions happen

Line 3-4: "+" as a unary operator----The conversion rules of an object to a basic data type under this operator:

(1). When the operand is the base data type, call the number () function and convert it to a numeric value

(2). When the operand is an object, call the object's ToString or valueof function, convert the object to a value of the base data type, and then call the number () function on the value.

Therefore, according to the above conversion rules, the output of the above result is a reasonable number.

But in the second rule, there's a big hole in it: whether to call ToString () or valueof (), and if two functions can convert objects to basic data types (such as objects of date type), who do you call?

This is similar to the following:

var x = {
  tostring:function () {return
    ' 0 ';
  valueof:function () {return
} var a = + x;  In this step, whether the call is ToString () or valueof (). , the + number as part of the two-element operator will give an explanation of
console.log (a);
Output results

Line 7-8: "+" as the two-dollar operator-----The conversion rules of an object to a basic data type under this operator:

When the "+" number as a 2-dollar operator is more complicated, because the "+" number can be used as a string connection, can also be as a number of addition minus. You can look up the conversion rule, how also has a 7, 8, the person who sees is dazzled to change. I went through a lot of testing, but also looked at some of the data, summed up the following laws:

Pseudo code,
A + B operation conversion Rules:
var Pa = toprimitive (a); var PB = toprimitive (b); if ((Pa is String) | | (Pb is String) {return Contacts (A, b) } if ((Pa is number) && (Pb are number)) {return a+b; } Throw error;
Note: The toprimitive is to convert the operand to the basic data type, give priority to call valueof, and if you get the basic data type, end, or continue to drop ToString (). (That is, valueof precedence is higher than ToString ())

With this in common, the + number as a unary operator conversion rule is essentially the same as a two-dollar operator, always giving precedence to valueof () when converting to a basic data type. Here's an example to verify:

1 var test = {
 2   valueof:function () {
 3 return     1;
 4   },
 5   tostring:function () {
 6 return     ' 0 ';
 7   }
 9 Console.log (+ test);   1
var result = test + test;
One console.log (result);  2

After talking about these, we can conclude by concluding that: the conversion between data types always invokes the valueof () function at the time of the operand operation (whether it is a unary or two-dollar operation), but the "+" number is used as the two-dollar operator when the precedence is applied to objects of the date type. was reversed (ToString has a higher priority).

Remember: the date type is a special case, when and only when the + number operation, and the "+" number as the two-dollar operator, toString () precedence call, such as the following,

var date=new date ();

Console.log (+date);  Still give priority to call valueof  
Console.log (date+ "ToString precedence is invoked");
Output results:
Thu 2015 11:44:48 gmt+0800tostring priority is called

(2): ToString () takes precedence over valueof () is called------when you want the output to be a string

When accessing variables of object type objects, when we use [] such square brackets, the contents of the square brackets are always first converted to strings, which is called the toString () function preferentially. Look at the following example:

1 var test = {
 2   tostring:function () {
 3 return     ' 0 '
 4   },
 5   valueof:function () {
   6 return     1;
 7   }
var object={};
One object[test]=1000;
Console.log (object);  Output Result: Object {0=1000}

The principles invoked at this point are described below:

[A] In this form of access:
var pa=toprimitive (a);
if (Pa is prmitive) {
var str=string (Pa);
Throw Error;//cannot Convert to String
[Str]//str is the form of a string
Note: toprimitive () calls the ToString () function first, and returns if the result is the base type, or continues to invoke valueof ();

There are also several examples of ToString precedence over valueof ()

object to direct output, precedence call ToString ()

Second, array conversion to string preference for ToString

3. Why is there such strange phenomena

As can be seen from the above, the two functions of ToString and valueof may be invoked at the time of conversion, but in different contexts the invocation is not of the same priority. These may be transparent to our programmers, but to the interpreter, they do a lot of work ... The bottom line: The interpreter always converts the context as much as possible to the result we want. Other words:

When an object is an operand, the interpreter always invokes valueof ()--(the object of the date type is the exception to the two-dollar "+" operation), whereas in other cases, the interpreter always thinks we want a string, so we call ToString () first.

Note: The date type Object invokes ToString () as a priority in the two-dollar + operation, and because in most cases, time is always used with string concatenation, and time and a number are not added together, so the date type has a higher priority for ToString ().

It is precisely because the interpreter always wants to produce the perfect output we want, it will cause this messy phenomenon and the rule appears. There is no perfect thing in the world, the spear and shield always depend on each other.

Understand the rules, to use the rules, to look back at the beginning of our first problem. Is it the rational use of these rules?

Digression: Writing this article is to show the importance of basic knowledge, not the pursuit of a bizarre program, the programmer should be the pursuit of plain code (Avenue to Jane) rather than these seemingly sibuxiang procedures, remember the cart before the horse.

In addition, after reading these are not a kind of back to read the impulse Ah, if there is, then my goal is reached ... Ha ha.

Note: tolocalestring () This function is to implement the localized output of strings, generally and ToString () output The same result, nothing special, is a normal function. In the date type, this function is overridden.

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: 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.