我有一个叫做tax
的类。
export class tax {
private _id: string;
private _name: string;
private _percentage: number;`
constructor(id: string = "", taxName: string = "", percentage: number = 0) {
this._id = id;
this._name = taxName;
this._percentage = percentage;
}
public get id(): string {
return this._id;
}
public set id(v: string) {
this._id = v;
}
public get name(): string {
return this._name;
}
public set name(v: string) {
this._name = v;
}
public get percentage(): number {
return this._percentage;
}
public set percentage(v: number) {
this._percentage = v;
}
toString(){
return this.id;
}
}
当我创建这个类的两个不同对象时,
a1: tax = new tax("id","name",4);
a2: tax = new tax("id","name",4);
console.log(a1 === a2); //false
console.log(a1 == a2); //false
当我比较a1和a2时,希望结果为true。 为了实现a1 === a2,我需要在我的类中进行哪些更改? 在税务类中我需要执行什么操作?或者我需要重写税务类中的哪个方法?
===
对于两个不同的对象返回true
。但是,你可以聪明地将 Tax 类转换为某种单例变体,这样它就不会为相同的参数构造新对象,而是返回先前的对象。然后a1 === a2
就会返回true
。 - dfsq