在Javascript中覆盖等价比较 [英] Override the Equivalence Comparison in Javascript

查看:205
本文介绍了在Javascript中覆盖等价比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Javascript中覆盖等价比较?

Is it possible to override the equivalence comparison in Javascript?

我最接近解决方案的方法是定义valueOf函数并使用加号调用valueOf对象的前面。

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.

这个有效。

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 了解更多细节。

That is because the == operator doesn't compare only primitives, therefore doesn't call the valueOf() function. Other operators you used do work with primitives only. I'm afraid you cannot achieve such thing in Javascript. See http://www.2ality.com/2011/12/fake-operator-overloading.html for some more details.

这篇关于在Javascript中覆盖等价比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆