1

我见过的最接近的是这个,但它并没有真正帮助我,因为我需要绑定一些参数以供以后使用 setInterval

进一步来说:

[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

可以看出,数组是用 解包的.apply(),但不是用.bind(). 有没有办法用 解包参数.bind()

4

2 回答 2

2

尝试这个。

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;
};

它将迭代地绑定array.

像这样使用它:

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

另请参阅下面@felix 的答案。这甚至很酷。

于 2016-02-06T02:47:26.027 回答
2

.bind只是另一个功能。.apply如果要使用参数数组调用它,请调用它:

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))
于 2016-02-06T03:05:07.740 回答