使用.bind()避免.call()和.apply() [英] Avoiding .call() and .apply() using .bind()

查看:148
本文介绍了使用.bind()避免.call()和.apply()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种完成某项任务的方法,那就是

I'm looking for a way to accomplish a certain task and that is, going from

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

when( promiseArray ).done(...)

您可能已经知道,.bind()可以用来创建诸如默认参数之类的东西,并且还可以做一些非常漂亮的事情.例如,而不是总是调用

As you might know, .bind() can get used to create something like default arguments and also doing some quite nifty stuff. For instance, instead of always calling

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

我们可以做到

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

这非常酷(即使调用这样的.bind()会导致性能下降,我也知道并且知道),但是我无法真正实现jQuerys .when调用.如果您有数量未知的承诺对象,通常可以将它们推入数组中,然后将其传递到.when中,就像上面的我的第一个代码片段一样.

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. 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.

到目前为止,我正在这样做:

I'm doing this so far:

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

现在我们可以像

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

这可行,但是我也想摆脱每次显式传递null的需要.所以我尝试了

This works, but I also want to get rid of the need to pass in null explicitly every time. So I tried

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

但这会惹上我:

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

我想我在这个问题上坐了太久了,不能再思考了.感觉有一个简单的解决方案. 我不想使用任何其他功能来解决此问题,我绝对更喜欢使用.bind()的解决方案.

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().

在此处查看完整的示例: http://jsfiddle.net/pp26L/

See a complete example here: http://jsfiddle.net/pp26L/

推荐答案

这应该有效:

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

您只需绑定(或咖喱,如果愿意).bind的第一个参数,并将其固定为null.

You just bind (or curry, if you prefer) the first argument of .bind and fix it to null.

小提琴 .

Fiddle.

这篇关于使用.bind()避免.call()和.apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆