How do I make a class's instances comparable and garbage collectable at the same time?

前端 未结 2 1036
一生所求
一生所求 2021-01-21 02:55

I\'m writing a class and want the instances to be comparable by <, >, ==.

For < and ><

2条回答
  •  抹茶落季
    2021-01-21 03:27

    First of all keep in mind that == is always worse than === because of such troubles. When you use x == y comparison where both operands are objects then js will compare them as objects. (more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) It is easy to test just running

    class ComparableObject {
      constructor(id) {
        this.id = id;
      }
    
      valueOf() {
        console.log("log", this.id);
        return this.id;
      }
    }
    
    new ComparableObject("12") == new ComparableObject(12);
    

    It will not produce any log but this:

    new ComparableObject("12") == new ComparableObject(12).valueOf();
    

    will print:

    log 12
    log 12
    true
    

    There are few solutions for your need:

    Number(new ComparableObject("12")) == Number(new ComparableObject(12));
    new ComparableObject("12").valueOf() == new ComparableObject(12).valueOf();
    

    GC cannot do something untill cache object will not remove references to instances.

提交回复
热议问题