Some code for example.
let a = 1 a.__proto__.toString = function(){ return 'test'} a.toString() //"test" a + '2' //"12"
I realy can't understand where is toString
method stored. If I do this with mutable objects I got
let o = {} o.__proto__.toString = function(){ return 'test'} o.toString() //"test" o + '2' //"test2"
That works as I expected. So the question is where toString
of Number
or other immutable types stored and called when type conversion occurs.
Object toString() Method in Java. Object class is present in java. lang package.
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
The toString() method is a built-in method of the JavaScript Number object that allows you to convert any number type value into its string type representation.
Return Value: The num. toString() method returns a string representing the specified number object.
So the question is where toString of Number or other immutable types stored and called when type conversion occurs
It's stored on Number.prototype
. The more important question is:
How is a number converted to a string when doing
1 + 'a'
?
Not via the toString
method!
The toString
method is only used when converting an object to a primitive value. However, a number is already a primitive value. Instead there is an internal ToString
routine that is called to convert the number to a string. The details can be found in the ES2017 specification at 12.8.3, 7.7.12 and 7.1.12.1 . The details are a bit long, but it starts like this:
- If
m
isNaN
, return the String"NaN"
.- If
m
is+0
or-0
, return the String"0"
.- ...
as you can see, these are very specific instructions for how to convert a number value to a string, which have nothing to do with the actual toString
method defined on Number.prototype.toString
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With