如何用null正确地调用fn.apply?

时间:2018-05-22 07:49:11

标签: javascript functional-programming apply built-in

背景:我想在一个带有多个参数的纯fn上映射一组参数数组。我认为currying应用null并且调用Array.map()会起作用。

[[x1, y1], [x2, y2], [x3, y3], ... [xn, yn]].map(curry(fn.apply, null))



var curry = function(fn, value) {
    return function (x, y) {
        return fn(value, x, y);
    };
}
var fn = (x,y) => [x, y];
var fn_c = curry(fn.apply, null)
fn_c([1,2]);


Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function
at <anonymous>:3:20
at <anonymous>:8:5

只有apply在curried函数中被记住,没有应用的fn。因此,curried函数尝试运行apply(x,y)而不是fn.apply(x,y),这当然失败了。

如何检索apply-ed函数以传递?

1 个答案:

答案 0 :(得分:0)

想出来。我忘了函数也是对象:

var curry = function(fn, value) {
    return function (x, y) {
        return fn(value, x, y);
    };
}
var fn = (x,y) => [x, y];
var fn_c = curry(Function.prototype.apply.bind(fn), null)
fn_c([1,2]);

......那很难看。我只是.map(params => fn.apply(null, params))