Summary of conversion of object types in JavaScript

Source: Internet
Author: User

The conversion of object-to-string and object-to-number types involves two important methods, and the resulting conversion results are affected by the results returned by both methods. These two methods are ToString and valueof. All objects inherit from object objects to both methods. The ToString method is used to return the string representation of an object (but in fact it is also possible to return a string). The ToString method, which inherits from object by default, does not return much meaningful content. The ValueOf method is intended to return an original type value that can represent an object, but because of the complexity of the object, in most cases it is not possible to represent it with a primitive type value. So the default valueof just returns the object itself. The date type is a special case, which is the only type of JavaScript predefined type that overrides the ToString and valueof methods.

The object type conversion string type step is as follows:

  1. If the object has the ToString method, the ToString method is called, and if the return is a primitive type, the original type is converted to a string (of course, if ToString returns a string, it is not required).
  2. If the object does not have a tostring method, or if ToString does not return the original type, it attempts to call the ValueOf method, and if the ValueOf method returns the original type, the original type is converted to a string (if the string is not needed if valueof is put back).
  3. If neither the ToString method nor the ValueOf method exist, or if their return type is not the original type, the TypeError exception is thrown.

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.