Search code examples
javascriptnumbersprototypeprototypejsvalue-of

How can I override the behavior of valueOf() as a prototype of the Number in JavaScript?


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


Solution

  • 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 to Object.create(Number.prototype) but if you want to do it on all Numbers, than you can go with a monkey patch:

    Number.prototype.toString = (function(f){return function(){return `whatever ${f.call(this)}`}})(Number.prototype.toString)
    
    Number.prototype.valueOf = (function(f){return function(){return f.call(this)}})(Number.prototype.valueOf)
    

    change the valueOf and toString to whatever you need.

    Warning: this is not good.