如何确定两个ES6类实例是否相等?

5
如何确定两个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,以比较实例属性而不是对象引用。

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

4
Rectangle 类中添加一个方法:
class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
  equals(rect) {
    return this.width == rect.width && this.height == rect.height;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接