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
,
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.
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?