如何确定两个 ES6 class 实例是否相等?
How to determine equality for two ES6 class instances?
如何判断两个ES6 class对象实例是否相等?例如:
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))
最后两个语句return false,但我希望它return true,比较实例属性,而不是对象引用。
添加一个方法到 Rectangle
class:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
equals(rect) {
return this.width == rect.width && this.height == rect.height;
}
}
如何判断两个ES6 class对象实例是否相等?例如:
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))
最后两个语句return false,但我希望它return true,比较实例属性,而不是对象引用。
添加一个方法到 Rectangle
class:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
equals(rect) {
return this.width == rect.width && this.height == rect.height;
}
}