Override the Equivalence Comparison in Javascript

后端 未结 5 470
一整个雨季
一整个雨季 2020-11-28 15:55

Is it possible to override the equivalence comparison in Javascript?

The closest I have gotten to a solution is by defining the valueOf function and invoking valueOf

5条回答
  •  眼角桃花
    2020-11-28 16:08

    Piggybacking on @Corkscreewe:

    This is because you are dealing with Objects and the equivalency operators are only going to compare whether two variables reference the same Object, not whether the two Objects are somehow equal.

    One solution is to use "+" in front of the variables and define a valueOf method for the Objects. This calls the valueOf method on each object to "cast" its value to a Number. You have already found this, but understandably do not seem very satisfied with it.

    A more expressive solution might be to define an equals function for your Objects. Using your examples above:

    Obj.prototype.equals = function (o) {
        return this.valueOf() === o.valueOf();
    };
    
    var x = new Obj(42);
    var y = new Obj(42);
    var z = new Obj(10);
    
    x.equals(y); // true
    x.equals(z); // false
    

    I know this doesn't do exactly what you want (redefine the equivalency operators themselves), but hopefully it will get you a little closer.

提交回复
热议问题