相关疑难解决方法(0)

在Javascript中覆盖等价比较

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

我得到的最接近的解决方案是定义valueOf函数并在对象前面用一个加号调用valueOf.

这有效.

equal(+x == +y, true);
Run Code Online (Sandbox Code Playgroud)

但这失败了.

equal(x == y, true, "why does this fail.");
Run Code Online (Sandbox Code Playgroud)

这是我的测试用例.

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); …
Run Code Online (Sandbox Code Playgroud)

javascript operator-overloading qunit

34
推荐指数
3
解决办法
3万
查看次数

标签 统计

javascript ×1

operator-overloading ×1

qunit ×1