Javascript: argument unpacking in function.prototype.bind()?
Javascript: argument unpacking in function.prototype.bind()?
我见过的最接近的是这个,但它并没有真正帮助我,因为我需要绑定一些参数以供以后与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()
来解开争论?
.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))
试试这个。
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的答案。这甚至很酷。
相关文章:
- 直接在函数声明上使用function.prototype.bind
- requestAnimationFrame的Function.prototype.bind导致属性不可读
- Snippet usefulness - Function.prototype.call.bind(Function.p
- 使用 Function.prototype.bind.apply(Obj, args) 将参数传递给对象,只传递第一个元
- Function.prototype.call.bind 是如何工作的
- 使用 Function.prototype.bind 或保存的引用
- Phantomjs Function.prototype.bind
- Function.prototype.bind with null 作为参数
- Mootools 何时使用 Function.prototype.bind
- Javascript: argument unpacking in function.prototype.bind()?
- 为什么使用Function.prototype.bind.apply
- JavaScript'有Ruby等价物吗;s函数.prototype.bind
- Array.prototype.map.bind与对象一起使用是否可靠
- 在没有上下文参数的情况下调用本机绑定函数(function.prototype.bind)
- 为什么Function.prototype.bind很慢?
- 在EventListeners上使用function.prototype.bind()
- 为什么使用Function.prototype.bind而不是Function.prototype.call ?
- Function.prototype.bind
- Javascript Function.prototype.bind的变化我想确保我理解
- 在回调中可以替代function.prototype.bind