Question on + and type conversions
P T Withington
ptw at pobox.com
Fri Dec 17 14:01:48 PST 2010
If I define an object with both valueOf and toString methods:
var color = {
valueOf: function () { return 0xff0000; }
,toString: function () { return 'red'; }
}
The rules of `+` result in:
color + 1 => 16711681
color + '' => '16711680'
This is because of:
> 11.6.1 The Addition operator(+)
> ...
> 7. If Type(lprim) is String or Type(rprim) is String, then
> a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
> ...
Is it intentional that after discovering that one of the operands' primitive value is a string, that toString is called on the other operand's primitive value, rather than its (original) value? Because I was hoping:
color + '' => 'red'
More information about the es-discuss
mailing list