【发布时间】:2020-05-07 17:18:44
【问题描述】:
我想用equals方法比较两个对象:
class test{
constructor(name, year) {
this.name= name;
this.year= year;
if (year== 0) {
this.year= -1;
}
}
equals(a){
if(this.year!= a.year){
return false;
}
if(this.name!= a.name){
return false
}
return true;
}
如果我调用类测试的新对象:
let a1 = new test("Hey",22);
let a2 = new test("Hey",22);
它适用于:
console.log(a1.equals(a2)); --> gives me true
但如果我在测试对象中生成一个新字符串:
let a1 = new test(new String("Hey"),22);
let a2 = new test(new String("Hey"),22);
equals 方法的输出给了我错误:
console.log(a1.equals(a2)); --> gives me false;
如何修复 equals 方法,以便它也比较 String 类型的新对象?
【问题讨论】:
标签: javascript object compare equals