Javascript 使用数组原型切片调用
以下代码(来自msdn)是“绑定”函数的简单实现:Javascript 使用数组原型切片调用,javascript,Javascript,以下代码(来自msdn)是“绑定”函数的简单实现: /* Approximation of `Function.prototype.bind` from ES5 (without error checking) */ Function.prototype.bind = function(thisArg) { var fn = this, args = *Array.prototype.slice.call(arguments, 1)*; return function() {
/* Approximation of `Function.prototype.bind` from ES5 (without error checking) */
Function.prototype.bind = function(thisArg) {
var fn = this, args = *Array.prototype.slice.call(arguments, 1)*;
return function() {
return fn.apply(thisArg, args.concat(*Array.prototype.slice.call(arguments, 0)*));
};
};
有人能解释一下对Array.prototype.slice.call的第一次调用吗?我知道参数不是数组,在使用slice和concat之前需要将其转换为数组。我不明白第一个呼叫-我们呼叫时不是失去了第一个元素吗
Array.prototype.slice.call(arguments, 1)?
你说得对
arguments
的第0个元素是thisArg
,这就是它被删除的原因。根据关于的文档,第一个参数(arguments[0]
)是自定义的this
值,用作bind
返回的函数(“绑定函数”)中的this
的值)
以下(arguments[1]
-arguments[n]
)是调用绑定函数时要添加的参数,以及调用时提供给的参数
第一个Array.prototype.slice.call
所做的是对传递给bind
call的参数进行切片,并从传递的第二个参数开始获取要预先添加的参数,留下第一个参数,它将是我们的this
比如说
var newFN = someFunction.bind(myNewThis,foo,bar,baz);
第一个Array.prototype.slice.call
采用foo
、bar
和baz
在返回的函数中,foo
、bar
和baz
在调用绑定函数时,在提供的参数前面加上前缀:
//fn - original function
//args - extracted arguments foo, bar and baz
//thisArg - the provided `this` value, myNewThis
//this code basically:
// - calls the original function (fn)
// - provides a custom `this` value (thisArg)
// - provides arguments that comprise the extracted arguments + the passed arguments
fn.apply(thisArg, args.concat(Array.prototype.slice.call(arguments, 0)));
因此,当您使用新的“绑定”函数时,您会得到一个自定义的this
值,以及一个“预设”的带前缀的参数列表:
newFN('ban','bam'); //arguments === ['foo','bar','baz','ban','bam'];
好的,这澄清了一点。但是,为什么需要在fn.apply中使用参数concat args?我认为,一旦我们创建了args变量,我们就会将其传递给apply。