How to bind function arguments without binding this?

前端 未结 15 907
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 07:25

In Javascript, how can I bind arguments to a function without binding the this parameter?

For example:

//Example function.
var c = funct         


        
相关标签:
15条回答
  • 2020-11-30 07:53
    var b = function() {
        return c(1,2,3);
    };
    
    0 讨论(0)
  • 2020-11-30 07:57

    In ES6, this is easily done using rest parameters in conjunction with the spread operator.

    So we can define a function bindArgs that works like bind, except that only arguments are bound, but not the context (this).

    Function.prototype.bindArgs =
        function (...boundArgs)
        {
            const targetFunction = this;
            return function (...args) { return targetFunction.call(this, ...boundArgs, ...args); };
        };
    

    Then, for a specified function foo and an object obj, the statement

    return foo.call(obj, 1, 2, 3, 4);
    

    is equivalent to

    let bar = foo.bindArgs(1, 2);
    return bar.call(obj, 3, 4);
    

    where only the first and second arguments are bound to bar, while the context obj specified in the invocation is used and extra arguments are appended after the bound arguments. The return value is simply forwarded.

    0 讨论(0)
  • 2020-11-30 07:57

    Well for the exemple you gave, this will do

    var b= function(callback){
            return obj.c(1,2,3, callback);
    };
    

    If you want to guarenty enclosure of the parameters :

    var b= (function(p1,p2,p3, obj){
            var c=obj.c;
            return function(callback){
                    return c.call(obj,p1,p2,p3, callback);
            }
    })(1,2,3,obj)
    

    But if so you should just stick to your solution:

    var b = obj.c.bind(obj, 1, 2, 3);
    

    It's the better way.

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