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()?

1
  • 1
    Seems I answered such a question before :P Commented Feb 6, 2016 at 3:14

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

I really like this. Very elegant - nice!
Question: since I think I found a solution without iteration, would this work as well, or if not, why?: ` Function.prototype.bindArray(thisArg, array) {` ` array.unshift(thisArg);` ` return this.bind.apply(this, array);` ` }`
This seems overly complex (for the task) and creates unnecessary intermediate function objects.
@13steinj yeah it works. This answer is actually cool.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.