The difference between valueof () and ToString () in JS

Source: Internet
Author: User
Tags numeric value object object

Basically, all JS data types have these two methods (except NULL), they solve the JS value operation and display problems, the following to see the difference between the two methods.
The valueof () method returns the original value of the Array object.
The ToString () method converts a logical value to a string and returns the result.

valueof () object return value

The elements of array arrays are converted to strings, separated by commas, and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean is a Boolean value.
The date is stored in UTC, which is the number of milliseconds from the beginning of Midnight January 1, 1970.
function functions themselves.
Number numeric value.
Object itself. This is the default condition. string literal value.

ToString () object action

Array converts the elements of an array to a string. The resulting string is separated by commas and is concatenated.
Boolean returns "true" if the Boolean value is true. Otherwise, returns "false".
Date returns the literal representation of the day. Error returns a string containing the associated error message.
The function returns a string with the following format, where functionname is the name of the called toString method function: function functionname () {[native code]}number the literal representation of the number returned.
String returns the value of a string object.
Returns "[Object ObjectName]" by default, where ObjectName is the name of the object type.

Test analysis

  code is as follows copy code

function Money (gold, silver, coin)
{
 this.gold = gold;
 this.silver = silver;
 this.coin = coin;
}

Money.parse = function (value)
{
 var coin = parseint (value%);
 var silver = parseint ( Value/25% 20);
 var gold = parseint (value/500);
 return new Money (gold, silver, coin);
}

Money.prototype.valueOf = function ()
{
 return (this.gold *) + this.silver) * + this.coi N
}

Money.prototype.toString = function ()
{
 return this.gold + "two gold," + This.silver + "two silver," + thi S.coin + "Wen Qian";
}

var money1 = new Money (5, 6, 1);
var money2 = new Money (2, 4, 6);

var Money3 = money.parse (money1 + money2);
Alert (Money3);

This implicitly calls the valueof and ToString, in the case of the two, in the numerical operation, the precedence call valueof, String operations, the first call to ToString. Like what
Money1 + Money2, the call is the two valueof after the value added, and alert, the Money3 first ToString.
This example is actually modeled on the JS built-in object date, and date is basically how the problem is handled.

The code is as follows Copy Code


function Money (n)
{
THIS.N = n;
}
Money.prototype.valueOf = function ()
{
Return THIS.N * 2
}
Money.prototype.toString = function ()
{
Return THIS.N * 3
}
var m1 = new Money (1);
var m2 = new Money (2);
m = m1 + m2
Alert (M1);
Alert (m2);
Alert (m);

I would like to add another article to you:

The code is as follows Copy Code

var AAA = {
I:10,
Valueof:function () {return this.i+30;},
Tostring:function () {return this.valueof () +10;}
}

Alert (AAA > 20); True
alert (+AAA); 40
Alert (AAA); 50

This results because they secretly invoke the valueof or ToString method.
But how do you tell which method is invoked, and we can test it in another way.
Because of the use of Console.log, please experiment in the FF containing Firebug!

  code is as follows copy code

var bbb = {
 i:10,
 tostring:function () {
  console.log (' toString ');
  return this.i;
&nbs P;},
 valueof:function () {
  console.log (' valueof ');
  return this.i;
 }

P>alert (BBB)//toString
Alert (+BBB);//valueof
Alert (' +bbb);//valueof
Alert (String (BBB));//10 ToString
Alert (number (BBB));//valueof
Alert (bbb = = ' ten ');//True valueof
Alert (bbb = = ' ten ');//false

The result gives the impression that if you call the ToString method when you convert to a string, you call the ValueOf method if you convert to a numeric value, but two of them are very discordant. One is alert ("+BBB"), and the string combination should be called the ToString method ... Another we can temporarily understand is that the = = = Operator does not convert implicitly, and therefore does not call them. In order to investigate the truth, we need more rigorous experiments.

The code is as follows Copy Code

var AA = {
I:10,
Tostring:function () {
Console.log (' toString ');
return this.i;
}
}
alert (AA);//ToString
alert (+AA); Ten toString
Alert (' +aa); Ten toString
Alert (String (AA)); Ten toString
Alert (number (AA)); Ten toString
Alert (aa = ' 10 '); True toString

Look at valueof again.

The code is as follows Copy Code

var bb = {
I:10,
Valueof:function () {
Console.log (' valueof ');
return this.i;
}
}

Alert (BB);//[Object]
alert (+BB); Ten valueof
Alert (' +bb); Ten valueof
Alert (String (BB)); [Object Object]
Alert (number (BB)); Ten valueof
Alert (BB = = ' 10 '); True valueof

Find it a little different?! It is not as uniform and regular as the above ToString.
For that [object], I guess I inherited it from object, and we'll take it out again.

The code is as follows Copy Code

Object.prototype.toString = null;
var cc = {
I:10,
Valueof:function () {
Console.log (' valueof ');
return this.i;
}
}


Alert (cc);//Ten valueof
alert (+CC); Ten valueof
Alert (' +cc); Ten valueof
Alert (String (cc)); Ten valueof
Alert (number (cc)); Ten valueof
alert (cc = = ' 10 '); True valueof

Summary: valueof in favor of operation, ToString is biased towards display.

1, when an object transformation (for example, alert (a)) is invoked, the ToString method is called preferentially, and if no ToString is overridden, the valueof method is invoked if neither method is overridden, but is output by object's ToString.
2, the ToString method is invoked preferentially when a strong-spin string type is made, and the valueof is invoked preferentially when the number is strongly converted.
3, in the case of operator operators, the valueof precedence is higher than ToString.

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.