184
rated 0 times
[
187]
[
3]
/ answers: 1 / hits: 54447
/ 12 Years ago, thu, may 10, 2012, 12:00:00
Is it possible to override the equivalence comparison in Javascript?
The closest I have gotten to a solution is by defining the valueOf function and invoking valueOf with a plus in front of the object.
This works.
equal(+x == +y, true);
But this fails.
equal(x == y, true, why does this fail.);
Here are my test cases.
var Obj = function (val) {
this.value = val;
};
Obj.prototype.toString = function () {
return this.value;
};
Obj.prototype.valueOf = function () {
return this.value;
};
var x = new Obj(42);
var y = new Obj(42);
var z = new Obj(10);
test(Comparing custom objects, function () {
equal(x >= y, true);
equal(x <= y, true);
equal(x >= z, true);
equal(y >= z, true);
equal(x.toString(), y.toString());
equal(+x == +y, true);
equal(x == y, true, why does this fails.);
});
Demo here: http://jsfiddle.net/tWyHg/5/
More From » operator-overloading