Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriden toString() is not called for Object of type Number [duplicate]

Why is toString() not called automatically in console.log("" + x)? The same situation is for 'alert' function. I read in many places that these functions convert objects to strings with toString() methods of the objects automatically.

Number.prototype.toString = function ()
{
  return "Hello!";
};

x = new Number(42);

console.log("" + x);
console.log("" + x.toString());

Before asking the question I was searching for the answer for about two hours. I saw this link Why does Boolean primitive not call prototype toString()?. It is something similar but it still does not answer my question. Would be very grateful for a clear explanation.

like image 536
JenyaKh Avatar asked Dec 06 '25 04:12

JenyaKh


1 Answers

You could change the valueOf method and use it for getting a primitive value.

Number.prototype.valueOf = function () {
    return "Hello!";
};

var x = new Number(42);

console.log("" + x);
console.log("" + x.toString());
like image 145
Nina Scholz Avatar answered Dec 09 '25 15:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!