Vin*_*sil 5 javascript equality class ecmascript-6
如何确定两个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))
Run Code Online (Sandbox Code Playgroud)
最后两个语句返回 false,但我希望它返回 true,以比较实例属性,而不是对象引用。
向类中添加一个方法Rectangle:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
equals(rect) {
return this.width == rect.width && this.height == rect.height;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1686 次 |
| 最近记录: |