MDN bind why concat arguments when calling apply

Deadly 提交于 2019-12-05 01:24:18

问题


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?


回答1:


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.




回答2:


No. As you log from x, x() arguments: are [1, 2, 3].

From bind2 you console.log(aArgs.concat(Array.prototype.slice.call(arguments)));, where aArgs = Array.prototype.slice.call(arguments, 1). So what else than [1, 2, 3, {value: 666}, 1, 2, 3] do you expect? Those are not the arguments passed to fnX, but those passed to bind: [{value: 666}, 1, 2, 3].

Inside the bound function, the aArgs variable still contains [1, 2, 3], while the arguments now are empty - you did call x().




回答3:


If you instead check the value of aArgs.concat(Array.prototype.slice.call(arguments)) from within fBound you'll see what you would expect. The key is that arguments refers to the additional arguments called on an already bound function.



来源:https://stackoverflow.com/questions/13003475/mdn-bind-why-concat-arguments-when-calling-apply

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