-1

I ran into this error of "Cannot read property 'localeCompare' of undefined"

when I was trying to convert a string function of compare(String, String) to String.compare(String)

   let compare = (y, x) =>  y.localeCompare(x) == 0 ? true : false;  //This works

   let gender = x =>  compare("male", x) || compare("female", x);  //This  works

   String.prototype.compareTruthy = (x) => {
    this.localeCompare(x) == 0 ? true : false;
   }

   "male".compareTruthy("male") //This does not work, why?

I wanted to re-use this compareTruthy function for any other string comparisons I might have later on.

What am I missing in my understanding?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Den
  • 1
  • 1
  • Arrow functions aren't a good choice for adding methods to the prototype... – jonrsharpe Jul 14 '19 at 19:55
  • Hello, can you please upvote this back up to 0, I cannot ask another question – Den Jul 14 '19 at 21:37
  • That's what's supposed to happen; if you demonstrate you can't write well received questions we don't *want* you asking more. See e.g. https://meta.stackexchange.com/questions/86997/what-can-i-do-when-getting-we-are-no-longer-accepting-questions-answers-from-th – jonrsharpe Jul 14 '19 at 21:40

1 Answers1

0

Arrow function expressions don't have the context of the current object. Read this page.

You need to use:

String.prototype.compareTruthy = function(x) {
    .....
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
DanKud
  • 221
  • 1
  • 4
  • I rewrote it to show this: String.prototype.compareTruthy = function (x) { this.localeCompare(x) == 0 ? true : false; } console.log("male".compareTruthy("male")); but it does not display anything in console – Den Jul 14 '19 at 20:09
  • N/m, thank you. I fixed the latter issue. – Den Jul 14 '19 at 20:12