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.
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());
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