Question:
Why is the number object not converting to a string? After all, I defined the toString
method in the prototype:
Number.prototype.toString = function() {
return "wrwer";
}
var a = 5;
console.log(a + '');
Answer:
You have overridden the method, and calling it manually produces the desired result:
Number.prototype.toString = function() {
return "wrwer";
}
var a = 5;
console.log(a.toString());
However, when using the addition operator, the toString
method is not called .
How this operator works can be seen in the ECMAScript specification .
In particular, since one of the operands ( ''
) is a string, the second ( a
) is also cast to a string. But this is done using the abstract operation ToString , which, in relation to numbers , forms a string according to the algorithm described in the specification, without calling the toString
method.
The standard implementation of the Number.prototype.toString
method uses ToString
internally if 10
passed in toString
as the base of the number system (or nothing is passed – 10
is the default). Otherwise (based on 2
to 9
and 11
to 36
), the algorithm depends on the implementation in a particular browser, but is unlikely to differ much from the standard one.