好的,让我们通过替换来解决这个问题。我们从以下内容开始:
Function.prototype.call.apply(Array.prototype.slice, arguments)
我们所知道的:
Function.prototype.call
是一个函数。
call
的 this
指向 Function.prototype
。
- 我们使用
apply
来改变 call
的 this
指针为 Array.prototype.slice
。
arguments
被应用到 call
中(而不是作为参数传递)。
因此,以上陈述等同于:
Array.prototype.slice.call(arguments[0], arguments[1], ...)
由此我们可以看出:
Array.prototype.slice
是一个函数。
slice
的this
指针指向Array.prototype
。
- 我们使用
call
改变slice
的this
指针为arguments[0]
。
arguments[1], ...
作为参数传递给slice
。
这与以下表达方式相同:
arguments[0].slice(arguments[1], ...);
这样做的好处是我们可以用一行代码创建一个快速未绑定包装器来包裹 slice
函数。
编辑:更好的创建快速未绑定包装器的方法是按照以下方式进行(请注意,它可能无法在某些旧浏览器中工作,但现在你不必担心这个问题-对于不支持bind
的浏览器,你可以始终使用shim):
var slice = Function.prototype.call.bind(Array.prototype.slice)
这与以下代码相同:
function slice() {
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
工作原理:
Function.prototype.call
是一个函数。
call
的 this
指针指向 Function.prototype
。
- 我们使用
bind
将 call
的 this
指针更改为 Array.prototype.slice
。
bind
返回一个函数,其 arguments
被应用于 call
。
奖励:如果您像我一样的高度功能编程风格,则会发现这段代码非常有用:
var funct = Function.prototype;
var obj = Object.prototype;
var arr = Array.prototype;
var bind = funct.bind;
var unbind = bind.bind(bind);
var call = unbind(funct.call);
var apply = unbind(funct.apply);
var classOf = call(obj.toString);
var ownPropertyOf = call(obj.hasOwnProperty);
var concatenate = call(arr.concat);
var arrayFrom = call(arr.slice);
- 使用这个方法,你可以轻松地使用
call
或者 apply
来创建无限制的封装。
- 你可以使用
classOf
方法来获取一个值的内部 [[Class]]
。
- 你可以在 for in 循环中使用
ownPropertyOf
方法。
- 你可以使用
concatenate
方法来连接数组。
- 你可以使用
arrayFrom
方法来创建数组。
Function.prototype.bind.call(Function.prototype.bind, Function.prototype.bind)
。 - BergiFunction.prototype.bind.bind(Function.prototype.bind)
相同。=) - Aadit M ShahFunction.prototype.bind.bind(Function.prototype.bind) === Function.prototype.bind.bind
从你的算法中... @AaditMShah - Stav Alfi