【问题标题】:Custom valueOf for a function in JSJS中函数的自定义valueOf
【发布时间】:2023-01-13 01:38:44
【问题描述】:

我有一个简单的效用函数,它以柯里化的方式将任意数量的数字相乘。我还为内部函数设置了 valueOf,所以现在 console(mult(10)(3)(2) 应该显示“60”。但实际上它显示的是“function 60”。这是一种不正确的使用方式吗? 或者 valueOf 不适用于函数?

这是代码:

var mult = function (y) {
    var that = this;
    that.x = y;
    that.f = function(s) {
        that.x = that.x * s;
        return that.f;
    }
    that.f.valueOf = function (){return that.x;};
    return that.f;
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    添加 valueOf 函数的目的是强制计算最终函数。您可以显式调用它

    console.log(mult(10)(3)(2).valueOf());
    

    或者在前面加上+

    console.log(+mult(10)(3)(2));
    

    var mult = function (y) {
        var that = this;
        that.x = y;
        that.f = function(s) {
            that.x = that.x * s;
            return that.f;
        }
        that.f.valueOf = function (){return that.x;};
        return that.f;
    }
    console.log(mult(10)(3)(2))
    console.log(mult(10)(3)(2).valueOf())
    console.log(+mult(10)(3)(2))

    【讨论】:

      【解决方案2】:

      您需要在 console.log 语句中调用 valueOf() 以强制执行评估:

      console.log(mult(10)(3)(2).valueOf());
      // 60
      

      JsFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-28
        • 2023-02-06
        • 1970-01-01
        相关资源
        最近更新 更多