MDN在调用apply时绑定为什么使用concat参数 [英] MDN bind why concat arguments when calling apply
问题描述
MDN为没有本机绑定方法的浏览器指定了polyfill绑定方法: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
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
这代码包含以下行:
aArgs.concat(Array.prototype.slice.call(arguments))
这是作为args传递给函数的apply方法:
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)));
但是,这一行实际上重复了参数,因此如果我将bind方法调用为:
However, this line actually repeats the arguments, so that if I called the bind method as:
fnX.bind({value: 666}, 1, 2, 3)
传递给fnX的参数是:
the arguments passed to fnX are:
[1, 2, 3, Object, 1, 2, 3]
运行以下示例并查看控制台输出 http://jsfiddle.net/dtbkq/
Run the following example and see the console output http://jsfiddle.net/dtbkq/
然而fnX报告的args是[1,2,3],这是正确的。有人可以解释为什么传递给apply调用时args是重复但是没有出现在函数参数变量中吗?
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).
第一次提到参数
是 bind的参数( )
,这将成为初始参数。
The first mention of arguments
are the arguments to bind()
, which will become initial arguments.
第二个提到的是绑定代理函数调用的下一组参数。因为参数
名称会影响其父参数
(以及此
需要分开的上下文),它们存储在名称 aArgs
。
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
.
这允许部分函数应用程序(有时称为 currying )。
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 。
这篇关于MDN在调用apply时绑定为什么使用concat参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!