Function.prototype.bind behaviour (call vs apply)

Juriy Zaytsev kangax.dev at gmail.com
Fri Aug 21 20:11:42 PDT 2009


On Aug 20, 2009, at 4:33 PM, Jordan Osete wrote:

> Hello everybody.
>
> The currently proposed bind() method for function objects behaves  
> like call(): it takes a number of arguments (from arguments[1]  
> onwards), and uses them for the function execution.
>
> Wouldn't it be more flexible to behave like apply(), taking an array  
> of parameters instead of taking each parameter individually ?
>
> The second approach seems more powerful to me. That is, every call()  
> can easyly be replaced by apply():
> func.call( thisObj, a, b, c ) -> func.apply( thisObj, [ a, b, c ] )
>
> ...But when you only have got an array of arguments, you can't go  
> the other way around:
> func.apply( thisObj, argsArray ) -> func.call( /* impossible */ )
>
> Would it be possible to change bind to behave like apply ?

If `boundArgs` is an array of arguments to bind, then I think you  
should be able to do this via something like:

Function.prototype.bind.apply(targetFn, [thisArg].concat(boundArgs));

// or maybe:

boundArgs.unshift(thisArg);
Function.prototype.bind.apply(targetFn, boundArgs);

Which is not very elegant of course (first version also takes a  
performance hit by creating unnecessary Array object).


-- 
kangax


More information about the es-discuss mailing list