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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With