如何将参数对象绑定到 JavaScript 中的函数?
How to bind an arguments object to a function in JavaScript?
有没有办法将 array/arguments 对象绑定到函数,类似于 .apply 允许使用参数数组调用函数的方式?
例如,我正在构建下划线库的一部分,我正在尝试 运行 使用传入的函数调用 .setTimeout
,并绑定参数列表。但是,.bind
似乎希望我单独列出每个参数。
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(func.bind(this, args), wait);
};
这不起作用。
这有点棘手,但您可以 .apply
.bind
方法。您只需要将要绑定的函数作为第一个参数传递,并将 this
参数作为数组的第一个索引传递。然后剩余的索引将作为参数传递。
工作示例:
var func = function(a, b, c) {
console.log(a, b, c);
};
setTimeout(func.bind.apply(func, [this, 1, 2, 3]), 100);
你必须构建你的 args
像这样的东西:
var args = Array.prototype.slice.call(arguments, 2);
args.unshift(this);
或者像这样:
var args = [this].concat(Array.prototype.slice.call(arguments, 2));
在 ES6 中:
func.bind(thisArg, ...argsArray)
这在幕后与另一个答案中显示的 bind.apply
相同。
然而,随着箭头函数的出现,我们似乎越来越少使用bind
。而不是写
func.bind(0, a, b, c)
这迫使我们指定一个 thisArg
第一个参数,即使我们不关心,我们现在可以写
() => func(a, b, c)
实际上更短。当然,我们总是能够将其写为
function() { return func(a, b, c); }
但那样会更冗长。
有没有办法将 array/arguments 对象绑定到函数,类似于 .apply 允许使用参数数组调用函数的方式?
例如,我正在构建下划线库的一部分,我正在尝试 运行 使用传入的函数调用 .setTimeout
,并绑定参数列表。但是,.bind
似乎希望我单独列出每个参数。
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(func.bind(this, args), wait);
};
这不起作用。
这有点棘手,但您可以 .apply
.bind
方法。您只需要将要绑定的函数作为第一个参数传递,并将 this
参数作为数组的第一个索引传递。然后剩余的索引将作为参数传递。
工作示例:
var func = function(a, b, c) {
console.log(a, b, c);
};
setTimeout(func.bind.apply(func, [this, 1, 2, 3]), 100);
你必须构建你的 args
像这样的东西:
var args = Array.prototype.slice.call(arguments, 2);
args.unshift(this);
或者像这样:
var args = [this].concat(Array.prototype.slice.call(arguments, 2));
在 ES6 中:
func.bind(thisArg, ...argsArray)
这在幕后与另一个答案中显示的 bind.apply
相同。
然而,随着箭头函数的出现,我们似乎越来越少使用bind
。而不是写
func.bind(0, a, b, c)
这迫使我们指定一个 thisArg
第一个参数,即使我们不关心,我们现在可以写
() => func(a, b, c)
实际上更短。当然,我们总是能够将其写为
function() { return func(a, b, c); }
但那样会更冗长。