Answer the question
In order to leave comments, you need to log in
Why are objects compared differently?
'use strict';
function A (name, age) {
this.name = name;
this.age = age;
return {
name: this.name,
age: this.age,
toString () {
return age;
}
};
}
function B (name, age) {
this.name = name;
this.age = age;
return {
name: this.name,
age: this.age,
toString () {
return age;
}
};
}
let a = new A("Ben", 30);
let b = new B("Gray", 30);
console.log(a == b); //false
console.log(a >= b); //true
Answer the question
In order to leave comments, you need to log in
Because objects are compared by reference, if two references lead to the same object, then you get true, otherwise - false. In order for the first and second cases to be true, the code must be seriously reworked, since it returns {...} each function call creates a new object, and returns. Using this inside functions A and B is not justified, it creates garbage. When comparing >= js tries to bring both operands to a number, and if memory serves, it first looks for the toValueOf method, and if it is not there, it leads to strings using the toString method, in your case there is a toString method, and since objects with the same field values age >= gives true, since toString is implicitly called from objects.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question