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

ecmascript-5, javascript, jquery

Solution

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.

Problem

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/

Original source