1

I was wondering, if there are any ways on how to compare 2 custom string objects which are instances of classes which extend String, using == doesn't work and it always returns false.

I have tried using valueOf but with no luck, the method gets never called if both operands are objects.

See an example below

class MyString extends String {
  doSomething(someData) {
    return doSomethingWithData(this, someData);
  };

  valueOf() {
    console.log('valueOf called');
    return this.toString();
  };
};

When doing console.log(new MyString('hi') == 'hi');, I Get

valueOf called
true

But When doing console.log(new MyString('hi') == new MyString('hi'));, I Get false.

So, the valueOf gets never called and the comparison blindly returns false, is there any possible way to fix it?

  • [Don't extend `String`](https://stackoverflow.com/q/58207487/1048572). [Don't create String objects](https://stackoverflow.com/q/5750656/1048572). And no, [you cannot overwrite equality between objects](https://stackoverflow.com/q/19620667/1048572). – Bergi Jun 14 '22 at 21:27
  • @Bergi I cannot not extend or not use the String objects, as I'm working on a library, and I need to add custom methods to the object. – Gamer Omega Jun 15 '22 at 08:02
  • Well no, you shouldn't need to do that. Provide static helper methods working on ordinary strings. – Bergi Jun 15 '22 at 17:15

0 Answers0