5

How to determine equality between two ES6 class object instances? For example:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

(new Rectangle(1, 1)) === (new Rectangle(1, 1))
(new Rectangle(3, 0)) === (new Rectangle(9, 3))

The last two statements return false, but I want it to return true, to compare the instance properties, instead of the object references.

vinibrsl
  • 6,563
  • 4
  • 31
  • 44
  • There is no operator overloading in JavaScript, and objects are compared by reference, not by property values. You'll need to define your own function to compare them. – Heretic Monkey Jan 11 '19 at 18:05
  • Well.... I want a jaguar, doesn't mean it will happen. You are doing a comparison between two memory references that are not pointing to the same address, this returning true would be wrong. You need to implement a method on the prototype of the constructor function that will recognize it's children by some means, the `===` is not what will get you the results sadly. – Dellirium Jan 11 '19 at 18:05
  • 5
    The best method would probably be to create an `.equals()` method – Sebastian Speitel Jan 11 '19 at 18:05

1 Answers1

4

Add a method to the Rectangle class:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
  equals(rect) {
    return this.width == rect.width && this.height == rect.height;
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Sam Alexander
  • 504
  • 1
  • 6
  • 24