MDN在调用apply时绑定为什么concat参数 [英] MDN bind why concat arguments when calling apply

查看:24
本文介绍了MDN在调用apply时绑定为什么concat参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN 为那些没有原生绑定方法的浏览器指定了一个 polyfill 绑定方法:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

这段代码有以下几行:

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

作为参数传递给函数上的apply方法:

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

然而,这一行实际上重复了参数,所以如果我调用 bind 方法为:

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

传递给 fnX 的参数是:

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

运行以下示例并查看控制台输出http://jsfiddle.net/dtbkq/>

然而,fnX 报告的参数是 [1, 2, 3],这是正确的.有人可以解释为什么传递给 apply 调用时 args 重复但没有出现在函数参数变量中吗?

解决方案

arguments 有两种不同的上下文.每次调用函数时,都会为所有传递的参数设置一个 arguments 对象(如果访问了 arguments).

首先提到的 argumentsbind() 的参数,它将成为初始参数.

第二个提到的是在绑定代理函数上调用的下一组参数.因为 arguments 名称会影响其父 arguments(以及需要分离的 this 上下文),所以它们存储在名称 <代码>aArgs.

这允许部分函数应用(有时称为currying).

var numberBases = parseInt.bind(null, "110");console.log(numberBases(10));console.log(numberBases(8));console.log(numberBases(2));

jsFiddle.

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.

这篇关于MDN在调用apply时绑定为什么concat参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆