1

The closest I've seen is this, but it doesn't really help me since I need to bind some parameters for later use with setInterval.

More specifically:

[in] var d = function(l, m) {
       console.log(l);
       console.log(m);
     }
[in] d.apply(window, [1,2])
[out] 1
[out] 2
[out-return-value] undefined
[in] d.bind(window, [1,2])()
[out] [1, 2]
[out] undefined
[out-return-value] undefined

As can be seen, arrays are unpacked with .apply(), but not with .bind(). Is there any way to unpack the arguments with .bind()?

Community
  • 1
  • 1
13steinj
  • 427
  • 2
  • 9
  • 16

2 Answers2

2

Try this.

Function.prototype.bindArray(ctx, array) {
  if (array && array.length && array.pop && array.length > 0) {
    var v = array.pop();
    return this.bindArray(ctx, array).bind(ctx, v);
  }
  else return this;
};

It will iteratively bind every value in array.

Use it like:

var d = function(l, m) {
  console.log(l);
  console.log(m);
};
var c = d.bindArray(null, [1,2]);
c(); // 1 2

Also see below @felix's answer. That's even cool.

Quarter2Twelve
  • 613
  • 1
  • 7
  • 14
2

.bind is just another function. Call it with .apply if you want to call it with an array of arguments:

var bound = d.bind.apply(d, [window, 1, 2]);
// If the `this` value is known, but the arguments is an array, concat:
// var bound = d.bind.apply(d, [window].concat(args))
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143