In Javascript, how can I bind arguments to a function without binding the this
parameter?
For example:
//Example function.
var c = funct
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.