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?

3
  • Don't extend String. Don't create String objects. And no, you cannot overwrite equality between objects. Commented Jun 14, 2022 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. Commented Jun 15, 2022 at 8:02
  • Well no, you shouldn't need to do that. Provide static helper methods working on ordinary strings. Commented Jun 15, 2022 at 17:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.