Javascript: function.prototype.bind() 中的参数解包?
Javascript: argument unpacking in function.prototype.bind()?
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.
更具体地说:
[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()
解压参数?
试试这个。
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 的回答。这甚至很酷。
.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))
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.
更具体地说:
[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()
解压参数?
试试这个。
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 的回答。这甚至很酷。
.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))