3

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.

2 Answers 2

2

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.

Working Example:

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));
3
  • why do you unsifting this from args? Actually, Does this referenced to window in your case?
    – The Reason
    Jun 30, 2016 at 21:39
  • @TheReason Unshift prepends the this object to the array so it will be the first argent passed to .bind. In their case, this would likely be the _ object. Run outside a method call, it would be the global object (window in a browser) or undefined if in strict mode. Jun 30, 2016 at 21:47
  • Ah, it works! This is definitely really tricky, and I can see why the actual underscore library just inserts and anonymous function returning a function with apply. Thanks!
    – Michael Du
    Jul 1, 2016 at 2:19
0

In ES6:

func.bind(thisArg, ...argsArray)

which under the covers amounts to the same thing as the bind.apply shown in another answer.

However, it seems that with the advent of arrow functions, we are using bind less and less. Rather than writing

func.bind(0, a, b, c)

which forces us to specify a thisArg first parameter even if we don't care, we can now write

() => func(a, b, c)

which is actually shorter. Of course we always have been able to write this as

function() { return func(a, b, c); }

but that would have been much more verbose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.