Rajesh
Rajesh

Reputation: 24945

Does String(number) call number.toString internally?

I was just trying something and found this:

If you call String(n) inside custom toString, it calls itself and throws error Maximum Call Stack exceeded,

JSFiddle

Number.prototype.toString = function() {
  return String(this)
}

var a = 10;
try {
  a.toString()
} catch (err) {
  console.log(err.message)
}

but if you call directly var b = String(a), it does not call toString function.

JSFiddle

Number.prototype.toString = function(){
  console.log(this);
  return '' + this;
}

var a = 10;
a.toString();

Note: I know above snippet is also throwing same error, but I have checked on Node, chrome - JSFiddle and Firefox - JSFiddle and it is consistent. var b = String(a) does not call number.toString(), so does '' + this. This is some optimisation in Stack snippet thats calling number.toString() on ''+this.

So my question is, what am I missing? Why is this weird behaviour?

Upvotes: 3

Views: 246

Answers (2)

Amit Jamwal
Amit Jamwal

Reputation: 649

May be you should use call/apply.

Number.prototype.toString = function() {
  console.log(this)
  return String(this)
}

var a = 10;
try {
  a.toString.call()
  console.log(a)
} catch (err) {
  console.log(err.message)
}

reason I think is The reason to use JS .call() method?

Upvotes: 0

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

Actual numbers invoke an internal method to convert them to string and their output is not affected by valueOf and toString, unless they are called explicitly.

So why is toString called in the first place then?

This is because in "sloppy" (non-strict) mode, the value of this will be converted to its object form (i.e. equivalent of new Number(10)) before being passed to String(this) or '' + this.

(For this reason, you might not see the difference between these two ways in normal applications where strict mode is used.)

As this is an object, both String() and the + addition operator will attempt to convert the object into a string. This is usually done by calling either obj.toString or obj.valueOf.

As for why String(this) fails but '' + this does not, the String function calls toString on the object before calling valueOf.

However, when you use the addition (+) operator, the order of valueOf and toString is reversed.

Upvotes: 4

Related Questions