Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is toString of Number stored?

Tags:

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.

like image 850
Александр Чиркин Avatar asked Jun 06 '18 22:06

Александр Чиркин


People also ask

What library is toString?

Object toString() Method in Java. Object class is present in java. lang package.

Where is toString defined?

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.

How are numbers converted to strings?

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.

What is the value of num toString ()?

Return Value: The num. toString() method returns a string representing the specified number object.


1 Answers

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:

  1. If m is NaN, return the String "NaN".
  2. If m is +0 or -0, return the String "0".
  3. ...

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.

like image 61
Felix Kling Avatar answered Oct 12 '22 22:10

Felix Kling