How to bind function arguments without binding this?

前端 未结 15 914
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题