Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MDN bind why concat arguments when calling apply

MDN specifies a polyfill bind method for those browsers without a native bind method: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

This code has the following line:

aArgs.concat(Array.prototype.slice.call(arguments))

Which is passed as the args to the apply method on the function:

fToBind.apply(this instanceof fNOP && oThis
                             ? this
                             : oThis,
                           aArgs.concat(Array.prototype.slice.call(arguments)));

However, this line actually repeats the arguments, so that if I called the bind method as:

fnX.bind({value: 666}, 1, 2, 3)

the arguments passed to fnX are:

[1, 2, 3, Object, 1, 2, 3] 

Run the following example and see the console output http://jsfiddle.net/dtbkq/

However the args reported by fnX are [1, 2, 3] which is correct. Can someone please explain why the args are duplicated when passed to the apply call but don't appear in the function arguments variable?

like image 599
Matt Avatar asked Oct 22 '12 00:10

Matt


1 Answers

The arguments are in two different contexts there. Each time a function is invoked, among other things, an arguments object is set to all the arguments passed (if the arguments is accessed).

The first mention of arguments are the arguments to bind(), which will become initial arguments.

The second mention are the next set of arguments called on the bound proxy function. Because the arguments name would shadow its parent arguments (as well as the this context needing to be separated), they are stored under the name aArgs.

This allows for partial function application (sometimes referred to as currying).

var numberBases = parseInt.bind(null, "110");

console.log(numberBases(10));
console.log(numberBases(8));
console.log(numberBases(2));

jsFiddle.

like image 80
alex Avatar answered Sep 28 '22 06:09

alex