Override the Equivalence Comparison in Javascript

后端 未结 5 472
一整个雨季
一整个雨季 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:07

    If it's full object comparison you're looking for then you might want to use something similar to this.

    /*
        Object.equals
    
        Desc:       Compares an object's properties with another's, return true if the objects
                    are identical.
        params:
            obj = Object for comparison
    */
    Object.prototype.equals = function(obj)
    {
    
        /*Make sure the object is of the same type as this*/
        if(typeof obj != typeof this)
            return false;
    
        /*Iterate through the properties of this object looking for a discrepancy between this and obj*/
        for(var property in this)
        {
    
            /*Return false if obj doesn't have the property or if its value doesn't match this' value*/
            if(typeof obj[property] == "undefined")
                return false;   
            if(obj[property] != this[property])
                return false;
        }
    
        /*Object's properties are equivalent */
        return true;
    }
    

提交回复
热议问题