I was given a task to understand the .toString and .valueOf methods, who calls them, where they are used, how they work, how they are called and how to change calling sequence.
I am getting an error when I trying to override this:
Number.prototype.toString = function () {
return "This is the number: " + this
};
Number.prototype.valueOf = function () {
//console.log(this)
return this;
}
console.log(new Number(33).toString());
console.log(new Number(34).valueOf())
Js returns an error RangeError: Maximum call stack size exceeded
, how can I override value of to return, for example, string – ‘The number is ${this}’
I’ve found out that everything is working if I remove console.log(new Number(33).toString());
I have tried to console.log this and got such output:
Code output
2
Answers
I really do not want to give this advice, and do not know why you wouldn’t declare a sub
Class
that has its prototype set toObject.create(Number.prototype)
but if you want to do it on all Numbers, than you can go with a monkey patch:change the
valueOf
andtoString
to whatever you need.Warning: this is not good.
When creating a
Number
usingnew
, you create aNumber object
, which is not a primitive – see MDN. That may be the origin of the error.I think there are better ways to override
Number
methods, without polluting itsprototype
.One of those is for example creating a custom
Number
object, using a closure to hold its value and extending that with some functions. That way you don’t needprotoype
(orthis
for that matter). Something like: