Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Defining a static method on a specific type in Javascript

I have a method that calculate a percentage increase between two values.
And in my "class" it looks like this:

percIncrease(a, b) {
    let percent;
    if (b !== 0) {
      if (a !== 0) {
        percent = ((b - a) / a) * 100;
      } else {
        percent = b * 100;
      }
    } else {
      percent = -a * 100;
    }
    return percent.toFixed(3);
  }

now cause I want it reusable from everywhere, I am trying to define it on a type (Number), so I can use it everywhere.

I tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Number.prototype.percIncrease = function (a, b) {
  let percent;
  if (b !== 0) {
    if (a !== 0) {
      percent = ((b - a) / a) * 100;
    } else {
      percent = b * 100;
    }
  } else {
    percent = -a * 100;
  }
  return percent.toFixed(3);
};

but if I try to use it like this :

Number.percIncrease(a,b);

TypeError: Number.percIncrease is not a function

I am not that good in using Javascript terms, but what I am actually trying, is to declare a static method on a specific type (say, Number).

How I would do this?

EDIT:

Or it doesn’t have to be static. Working on a value would do the job to. For example this (pseudo code):

myNumber.percIncrease(inCompareToValue: anotherNumber)

>Solution :

When you define a method in the prototype, it’s used when you call the method on an instance. Static methods should be added to the type directly, not the prototype:

Number.percIncrease = function (a, b) {
  let percent;
  if (b !== 0) {
    if (a !== 0) {
      percent = ((b - a) / a) * 100;
    } else {
      percent = b * 100;
    }
  } else {
    percent = -a * 100;
  }
  return percent.toFixed(3);
};

console.log(Number.percIncrease(10, 15));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading