Is there a way to bind an array/arguments object to a function, similar to how .apply allows for calling a function with an array of arguments?
For instance, I am building parts of the underscore library, and I'm trying to run call .setTimeout with the function that is passed in, and binding the list of arguments. However, it seems like .bind is expecting me to list out every argument individually.
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(func.bind(this, args), wait);
};
This isn't working.
It's a little tricky, but you can .apply the .bind method. You just need to pass the function you are binding to as the first argument, and the this argument as the first index of the array. Then the remaining indexes will be passed as arguments.
var func = function(a, b, c) {
console.log(a, b, c);
};
setTimeout(func.bind.apply(func, [this, 1, 2, 3]), 100);
You'll have to construct your args something like this:
var args = Array.prototype.slice.call(arguments, 2);
args.unshift(this);
Or something like this:
var args = [this].concat(Array.prototype.slice.call(arguments, 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With