0

I currently have a String.protype called isColor, which is checking the color. But i dont want it to have an argument inside the function.

I want to archive something like this:

const color = 'red';

console.log(color.isColor());

expected output: true

1 Answers1

1

Inside the method, compare the this (the instance) against whatever you're comparing it against:

String.prototype.isColor = function() {
  return ['red', 'orange', 'yellow'].includes(String(this));
}
console.log('red'.isColor());
console.log('somethingElse'.isColor());

You need the String to convert the this if you run the script in sloppy mode, in which case this will be a string object, not a string primitive, so you need to turn it into a primitive before comparison.

But keep in mind that mutating built-in prototypes is very bad practice - you should strongly consider using a different approach, if at all possible.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320