Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind an arguments object to a function in JavaScript?

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.

like image 541
Michael Du Avatar asked May 12 '26 04:05

Michael Du


1 Answers

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));
like image 100
Alexander O'Mara Avatar answered May 14 '26 19:05

Alexander O'Mara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!