Avoiding .call() and .apply() using .bind()

只愿长相守 提交于 2019-12-04 10:31:21

问题


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

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

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


回答1:


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.

Fiddle.




回答2:


bind accepts a variable number of arguments, so you can partially apply a method. 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/



来源:https://stackoverflow.com/questions/10247807/avoiding-call-and-apply-using-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!