Javascript 如何确定两个ES6类实例的相等性?

Javascript 如何确定两个ES6类实例的相等性?,javascript,class,ecmascript-6,equality,Javascript,Class,Ecmascript 6,Equality,如何确定两个ES6类对象实例之间的相等性?例如: 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)) 最后两条语句返回false,但我希望

如何确定两个ES6类对象实例之间的相等性?例如:

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))

最后两条语句返回false,但我希望它返回true,以比较实例属性,而不是对象引用。

矩形
类添加一个方法:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
  equals(rect) {
    return this.width == rect.width && this.height == rect.height;
  }
}

JavaScript中没有运算符重载,对象通过引用而不是属性值进行比较。您需要定义自己的函数来比较它们。嗯。。。。我想要一辆捷豹,但这并不意味着它会发生。当您在两个不指向同一地址的内存引用之间进行比较时,返回true是错误的。您需要在构造函数的原型上实现一个方法,该方法将通过某种方式识别它的子函数,
==
不会让您得到结果。最好的方法可能是创建一个
.equals()
方法