相关疑难解决方法(0)

在JavaScript中重载算术运算符?

考虑到这个JavaScript"类"定义,这是我能想到的最好的方法来解决这个问题:

var Quota = function(hours, minutes, seconds){
    if (arguments.length === 3) {
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;

        this.totalMilliseconds = Math.floor((hours * 3600000)) + Math.floor((minutes * 60000)) + Math.floor((seconds * 1000));
    }
    else if (arguments.length === 1) {
        this.totalMilliseconds = hours;

        this.hours = Math.floor(this.totalMilliseconds / 3600000);
        this.minutes = Math.floor((this.totalMilliseconds % 3600000) / 60000);
        this.seconds = Math.floor(((this.totalMilliseconds % 3600000) % 60000) / 1000);
    }

    this.padL = function(val){
        return (val.toString().length === 1) ? "0" + val : val;
    }; …
Run Code Online (Sandbox Code Playgroud)

javascript operator-overloading

68
推荐指数
8
解决办法
6万
查看次数

在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 ×2

operator-overloading ×2

qunit ×1