简体   繁体   English

使用.bind()避免使用.call()和.apply()

[英]Avoiding .call() and .apply() using .bind()

I'm looking for a way to accomplish a certain task and that is, going from 我正在寻找一种方法来完成某项任务,即从中开始

jQuery.when.apply( null, promiseArray ).done(...)

to

when( promiseArray ).done(...)

As you might know, .bind() can get used to create something like default arguments and also doing some quite nifty stuff. 您可能知道, .bind()可以用来创建类似默认参数的东西,也可以做一些非常漂亮的东西。 For instance, instead of always calling 例如,而不是总是打电话

var toStr = Object.prototype.toString;
// ...
toStr.call([]) // [object Array]

we can do it like 我们可以这样做

var toStr = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]

This is fairly cool (even if there is a performance penality invoking .bind() like this, I know it and I'm aware of it), but I can't really accomplish it for jQuerys .when call. 这是相当酷的(即使有一个性能阴谋调用.bind()这样,我知道它,我知道它),但我不能真正完成jQuerys .when调用时。 If you got an unknown amount of promise objects, you usually push those into an array, to then be able to pass those into .when like in my first code snippet above. 如果你有一个未知数量的promise对象,你通常将它们推入一个数组,然后就可以将它们传递给.when就像我上面的第一个代码片段一样。

I'm doing this so far: 我到目前为止这样做:

var when = Function.prototype.apply.bind( $.when );

Now we can go like 现在我们可以去

when( null, promiseArray ).done(...)

This works, but I also want to get rid of the need to pass in null explicitly every time. 这有效,但我也想摆脱每次都明确传入null的需要。 So I tried 所以我试过了

var when = Function.prototype.apply.bind( $.when.call.bind( null ) );

but that throws at me: 但那引起了我的注意:

"TypeError: Function.prototype.apply called on incompatible null"

I guess I'm sitting over this for too long now and can't think straight anymore. 我想我现在坐在这已经太久了,不能再思考了。 It feels like there is an easy solution. 感觉就像有一个简单的解决方案。 I don't want to use any additional function to solve this issue, I'd absolutely prefere a solution using .bind() . 我不想使用任何其他功能来解决这个问题,我绝对会优先使用.bind()来解决问题。

See a complete example here: http://jsfiddle.net/pp26L/ 请在此处查看完整示例: http//jsfiddle.net/pp26L/

This should work: 这应该工作:

when = Function.prototype.apply.bind( $.when, null);

You just bind (or curry, if you prefer) the first argument of .bind and fix it to null . 你只需绑定(或curry,如果你愿意) .bind的第一个参数并将其修复为null

Fiddle . 小提琴

bind accepts a variable number of arguments, so you can partially apply a method. bind接受可变数量的参数,因此您可以部分应用方法。 So, instead of: 所以,而不是:

var when = Function.prototype.apply.bind( $.when );

Do this: 做这个:

var when = Function.prototype.apply.bind( $.when , null );

And updated jsfiddle: http://jsfiddle.net/pp26L/2/ 并更新了jsfiddle: http//jsfiddle.net/pp26L/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM