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