比较javascript中的基本数据类型和对象数据类型

比较javascript中的基本数据类型和对象数据类型,javascript,object,compare,equals,Javascript,Object,Compare,Equals,我想用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 fal

我想用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方法的输出为false:

console.log(a1.equals(a2)); --> gives me false;
如何修复equals方法,使其同时比较字符串类型的新对象?

请参见下面的示例:

var s=‘foo’; var s_obj=新字符串; var s_obj2=新字符串; 控制台。日志类型; 控制台。s_obj的日志类型; 控制台日志 console.logs_obj console.logs_obj.valueOf //搞笑效果: console.logs\u obj==s//true console.logs==s_obj//true console.logs_obj==s_obj2//false console.logs_obj.valueOf==s//true
console.logs_obj.valueOf==s_obj2.valueOf//trueof如果typeof name是对象a.name和this.name,则必须使用.valueOf。我编辑我的示例是为了给你一些有趣的console.log