JS in ToString () & ValueOf ()

Source: Internet
Author: User
Tags arithmetic operators object object

Conversion of data

All objects inherit two conversion methods:

The first is ToString (), whose function is to return a string that reflects the object

The second is valueof (), whose function is to return its corresponding original value

ToString ()

ToString () can be seen as converting a data into the form of a corresponding string, Yasuteru this conversion rule

Use the sample:

//returns the corresponding stringConsole.log ({x:1, y:1}). ToString ()); //[Object Object]Console.log ([1,2,3].tostring ());// theConsole.log ((function(x) {f (x);}). ToString ());//function (x) {f (x);}Console.log (/\d+/g.tostring ());///\d+/gConsole.log (NewDate (2015,4,4). toString ());//Mon may 00:00:00 gmt+0800Console.log (NewDate (2015,4,4). ValueOf ());//1430668800000

ValueOf ()

The ValueOf method definition differs for each JavaScript intrinsic object.

Object return value
Array The elements of the array are converted to strings, which are separated by commas and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean A Boolean value.
Date The stored time is the number of milliseconds that are counted from midnight January 1, 1970 UTC.
Function function itself.
Number numeric value.
Object The object itself. This is the default condition.
String The string value.

The Math and Error objects do not have a valueOf method.

--------------------------------------------------------------------------------------------------------------- ---------------

In general, the conversion of an object to a string passes through the following steps:

1. Call this method if the object has the ToString () method. If it returns a primitive value, JS converts the value to a string and return the string result.

2. If the object does not have the ToString () method, or if the method does not return a raw value, then JS calls the ValueOf () method.

3. Otherwise, JS cannot get a raw value from ToString () or valueof (), so it throws a type error exception.

In general, the object-to-digital conversion process, JS did the same thing, but here it will first try to use the valueof () method:

1. If the object has the valueof () method, which returns a primitive value, JS converts the original value to a number and returns the number.

2. Otherwise, if the object has the ToString () method, which returns a raw value, JS will be converted and returned.

(first JS converted to the corresponding string original value, and then continue to convert the original value to the corresponding number type, and then return the number)

3. Otherwise, JS throws a type error exception.

var New String (' Hello,world '); Console.log (typeof//' object 'console.log (typeof  //' string '

For all non-date objects, the conversion of an object to the original value is essentially an object-to-number conversion

(The valueof is called first, but the date object uses the object-to-string conversion mode, but the conversion is performed once and immediately, and is not converted to a string and then to the corresponding number type as described above)

For example, the "+" operator in JS can perform mathematical addition and string join operations.

If one of his operands is an object, JS will use a special method to convert the object to the original value instead of using the method of other arithmetic operators to perform the object-to-number conversion, similar to the "= =" operator

Like "= =", "<" and other operators also do the conversion of the object to the original value, but the special case of the date object to go out

The "-" minus operator converts two operands to a number

Like what:

varnow =NewDate (); Console.log (now); //Date {Sat 13:21:08 gmt+0800}Console.log (typeof(now+1));//stringConsole.log ((now+1));//Sat Apr 13:21:08 gmt+08001Console.log (typeof(now-1));// NumberConsole.log ((now-1));//1428124868474Console.log (now = = now.tostring ());//trueConsole.log (now > Now-1);//true
var New  var date_string =var date_value =//true // false

--------------------------------------------------------------------------------------------------------------- -----------------

More detailed examples of use:

(Excerpt from:http://www.jb51.net/article/32327.htm)

var aaa =tenfunctionreturnthis. i+30function  returnthis. valueOf () +10/  /// //

This results because they secretly invoke the valueof or ToString method. Further testing

varBBB ={i:10, toString:function() {Console.log (' ToString '); return  This. I;}, ValueOf:function() {Console.log (' ValueOf '); return  This. I;} } alert (BBB);//Ten toStringalert (+BBB);//Ten valueOfAlert (' +bbb ');//Ten valueOfAlert (String (BBB));//Ten toStringAlert (number (BBB));//Ten valueOfAlert (bbb = = ' 10 ');//true ValueOfAlert (bbb = = = ' 10 ');//false

At first glance, it is probably a feeling that if you call the ToString method when converting to a string, the ValueOf method is called if it is converted to a numeric value, but two of them are very discordant.

One is alert (' +bbb '), the string should be called the ToString method ... Another we can understand for the time being that the = = = operator does not make implicit conversions, so they are not called.

To pursue the truth, we need more rigorous experimentation.

varAA ={i:10, toString:function() {Console.log (' ToString '); return  This. I;} } alert (AA);//Ten toStringalert (+AA);//Ten toStringAlert (' +aa ');//Ten toStringAlert (String (AA));//Ten toStringAlert (number (AA));//Ten toStringAlert (aa = = ' 10 ');//true toStringlook at valueof again. varBB ={i:10, ValueOf:function() {Console.log (' ValueOf '); return  This. I;} } alert (BB);//[Object Object]alert (+BB);//Ten valueOfAlert (' +bb ');//Ten valueOfAlert (String (BB));//[Object Object]Alert (number (BB));//Ten valueOfAlert (BB = = ' 10 ');//true ValueOffound a little different?! It is not as uniform as the above ToString. For that [object object], I would expect to inherit from object, and we'll take it out again. Object.prototype.toString=NULL; varCC ={i:10, ValueOf:function() {Console.log (' ValueOf '); return  This. I;} } alert (cc);//Ten valueOfalert (+CC);//Ten valueOfAlert (' +cc ');//Ten valueOfAlert (String (cc));//Ten valueOfAlert (number (cc));//Ten valueOfalert (cc = = ' 10 ');//true ValueOf

The sum up is that if you rewrite only ToString, the object conversion ignores the existence of valueof to convert.

However, if only the ValueOf method is overridden, the valueof method is preferred when converting to a string. In the case where ToString cannot be called, only valueof can be made to battle.

JS in ToString () & ValueOf ()

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.