0

I want to compare two objects with a equals method:

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;
    }

if i call a new Object of the class test:

let a1 = new test("Hey",22);
let a2 = new test("Hey",22);

it works fine for:

console.log(a1.equals(a2)); --> gives me true

but if i generate a new String in the test Object:

let a1 = new test(new String("Hey"),22);
let a2 = new test(new String("Hey"),22);

the output of the equals method gives me false:

console.log(a1.equals(a2)); --> gives me false;

How can i fix the equals method so it also compares a new Object of the type String?

Barmar
  • 741,623
  • 53
  • 500
  • 612
lks95
  • 25
  • 1
  • 1
  • 5

1 Answers1

0

See the example below:

var s = 'foo';
var s_obj = new String(s);
var s_obj2 = new String(s);

console.log(typeof s); 
console.log(typeof s_obj);  

console.log(s)
console.log(s_obj)
console.log(s_obj.valueOf())

// funny effects:
console.log(s_obj==s) // true 
console.log(s==s_obj) // true
console.log(s_obj==s_obj2) // false
console.log(s_obj.valueOf()==s) // true
console.log(s_obj.valueOf()==s_obj2.valueOf()) // true

if you compare two new String objects you're not comparing their values inside, but the objects instance

Max
  • 1,020
  • 7
  • 13
  • if typeof name is object (both a.name and this.name) then you have to use .valueOf. I edit my example to give you some funny console.log – Max Jan 21 '20 at 16:07