使用javascript .bind()方法跳过参数 [英] Skipping an argument using the javascript .bind() method
问题描述
在JavaScript中,我可以将参数绑定到类似这样的函数.
In JavaScript I can bind arguments to a function like so..
function foo(arg1, arg2) { console.log(arguments); }
foo = foo.bind(this, 'bar');
被调用时,我们得到此输出...
When called, we get this output...
foo('baz');
> { '0': 'bar', '1': 'baz' }
是否可以跳过.bind()函数中的参数以实现以下输出?
Is it possible to skip arguments in the .bind() function to achieve the following output?
function foo(arg1, arg2, arg3, arg4) { console.log(arguments); }
foo = foo.bind(this, 'bar', null, 'qux');
foo('baz', 'lel');
> { '0': 'bar', '1': 'baz', '2': 'lel', '3': 'qux' }
推荐答案
看看Underscore的 _.partial
:
Take a look at Underscore's _.partial
:
通过填充任意数量的参数来部分应用函数,而无需更改其动态this值.您可以在参数列表中传递_,以指定不应预先填充但在调用时可以随时提供的参数.
在您的情况下:
function foo(arg1, arg2, arg3, arg4) { console.log(arguments); }
foo = _.partial(foo, 'bar', _, 'qux');
foo('baz', 'lel');
> { '0': 'bar', '1': 'baz', '3': 'qux', '4': 'lel'}
是的,我知道这与您所说的不完全相同.您似乎希望将两个参数都压缩在 _
所在的位置.除了明确指定在调用时将填充两个参数之外,没有其他解决方法:
Yes, I know this is not exactly what you said you wanted. You seem to want both arguments to be squeezed in where the _
is. There is no good way around that other than explicitly specifying that two arguments will be filled in at the time of call:
foo = _.partial(foo, 'bar', _, _, 'qux');
我不一定建议您使用它,但是至少您可以看一下他们的代码并获得一些提示.
I am not necessarily recommending that you use this, but at least you could take a look at their code and get some hints.
如果您希望始终有预定的参数,例如'qux'
,那么您将需要一些其他机制.例如,这是一个小例程(使用ES6,但您可以调整),它将一个函数转换为一个将指定参数放在参数列表末尾的函数:
If you want to have predetermined arguments always come at the end, like 'qux'
, you will need some additional machinery. For instance, here's a little routine (using ES6, but you can adapt), that transforms a function into one where specified parameters are placed at the end of the argument list:
function partialEnd(fn, ...predefinedArgs) {
return function() {
return fn.apply(this, [...arguments, ...predefinedArgs]);
};
}
您可以这样使用:
function foo(a, b, c) { console.log(a + b + c); }
foo = partialEnd(foo, 3);
foo(1, 2) // outputs 6
您可以使用 _
占位符将其与 _.partial
结合使用,以获得将某些参数插入参数列表,而其他参数始终放在末尾的效果:
You could combine this with _.partial
using _
placeholders to obtain an effect where some parameters are inserted into the argument list, and others are always placed at the end:
function foo(arg1, arg2, arg3, arg4) { console.log(arguments); }
foo = _.partial(foo, 'bar', _, _);
foo = partialEnd(foo, 'lel');
foo('baz', 'lel');
> { '0': 'bar', '1': 'baz', '3': 'lel', '4': 'qux'}
这篇关于使用javascript .bind()方法跳过参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!