Using bind for partial application without affecting the receiver

后端 未结 1 1449
名媛妹妹
名媛妹妹 2021-01-25 23:53

If I want to partially apply a function I can use bind, but it seems I have to affect the receiver of the function (the first argument to bind). Is thi

相关标签:
1条回答
  • 2021-01-26 00:34

    partial application using bind without affecting the receiver

    That's not possible. bind was explicitly designed to partially apply the "zeroth argument" - the this value, and optionally more arguments. If you only want to fix the first (and potentially more) parameters of your function, but leave this unbound, you'll need to use a different function:

    Function.prototype.partial = function() {
        if (arguments.length == 0)
            return this;
        var fn = this,
            args = Array.prototype.slice.call(arguments);
        return function() {
            return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
        };
    };
    

    Of course, such a function is also available in many libraries, e.g. Underscore, Lodash, Ramda etc. There is no native equivalent however.

    0 讨论(0)
提交回复
热议问题