Home > Software design >  Convert toUSD(amount) function to prototype function. How?
Convert toUSD(amount) function to prototype function. How?

Time:01-29

I have the following function that works fine.

function toUSD(amount): string {
  // RETURN number in $0.00 format
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
};

I use it like this:

console.log(toUSD(123)); // output = $123.00

What would I need to change to use it like this?

console.log((123).toUSD()); // output = $123.00

CodePudding user response:

Your function should not use input parameters to pass the value. You have to refer to the current number using this:

function toUSD(this: number): string {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(this);
};

Then you can assign it to Number.prototype as also suggested by Ximaz' answer:

Number.prototype.toUSD = toUSD;

After that, you can call it like (123).toUSD() which outputs $123.00.

CodePudding user response:

I think the right way to use the prototype thing would be like so :

function toUSD(this: number) { ... }     // Your declaration

Number.prototype.toUSD = toUSD // Assigns the prototype to Number class

console.log((123).toUSD());    // output = $123.00

By looking at the solution I found out mine isn't working because I was not aware of the this keyword, my bad, I learned something too lol.

Unfortunatelly the output on my computer is $NaN but the fact that it actually displays something means that the pototype's call worked.

(Judging by the solving answer, it's because I forgot the this keyword, mb)

  • Related