In Javascript, how can I bind arguments to a function without binding the this
parameter?
For example:
//Example function.
var c = funct
var b = function() {
return c(1,2,3);
};
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.
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.