是否可以重写 Javascript 中的等价比较?
我得到的最接近的解决方案是定义 valueOf 函数并在对象前面加上加号来调用 valueOf 。
这有效。
equal(+x == +y, true);
但这失败了。
equal(x == y, true, "why does this fail.");
这是我的测试用例。
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.");
});
演示在这里:http://jsfiddle.net/tWyHg/5/
那是因为==
运算符不只比较基元,因此不会调用valueOf()
功能。您使用的其他运算符仅适用于基元。恐怕你无法用 Javascript 实现这样的事情。看http://www.2ality.com/2011/12/fake-operator-overloading.html了解更多详细信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)