Original article: enforcing tostring ()
Translation: Javascript
Tostring ()
Translator: singleseeker
Javascript will automatically convert the value to the desired type based on the needs of methods or operators, which may lead to various errors. Brian McKenna (@ puffnfresh) suggests provides the following test code:
Object.prototype.valueOf = function () { throw new Error('Use an explicit toString');};
What are the effects of these codes? You can no longer use the plus sign operator to convert an object into a string:
> var obj = {};> 'Hello '+objError: Use an explicit toString> String(obj)'[object Object]'> obj.toString()'[object Object]'> 'Hello '+String(obj)'Hello [object Object]'
What is this? To convert an object to a specific basic type T, first, its value is converted to a basic type, and then to T. The previous conversion is completed in two steps:
CallvalueOf()Method. If a basic type is returned, it ends.
Otherwise, call the MethodtoString(). If a basic type is returned, end
Otherwise, an error is thrown.
If the final conversion is a numeric value, it is calledvalueOf()AndtoString().
If the final conversion is a stringtoStringWill be called first. The plus sign operator may be converted into a numeric or string type, but it usually produces a basic type based on numeric operations.
Code snippets that do not need to be sent at the beginning of the article,Object.prototype.valueOf()The object itself will be returned. This is a method that continues from the native object without being overwritten:
> var obj = {};> obj.valueOf() === objtrue
The plus sign operator will eventually calltoString(). The code snippet above blocks the call and throws an error before the method can be called.
Note that this error message is not always correct.
> Number(obj)Error: Use an explicit toString
However, this trick is useful.
If an object really wants to be converted into a number, it still needs to call its ownvalueOfMethod.
@ Singleseeker: I really want to translate this article, but it is good to summarize the knowledge points, however, as an English Technical article written by a foreigner who is not a mother-tongue English language, I am a cainiao translator who is not a mother-tongue English.
The following is a summary.
UsuallyvaluOf()Indicates that an unconverted object is returned, that is, its own
In additionDateAlmost all objects are called first.valueOf()Method
IfvalueOf()Returns a clear basic value type. when an object is added to a string,toString()Will not be called
Reference
Forced conversion object (objects) to original value (primitives)
In JavaScript, how much is {} + {} equal?