可能重复:
链接呼叫和一起应用的含义是什么?
我发现了一些这样的代码:
function fun() {
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
Run Code Online (Sandbox Code Playgroud)
我知道call
和apply
js,但是当他们走到一起时我很困惑.
然后我想知道是否
Function.prototype.call.apply(Array.prototype.slice, arguments)
Run Code Online (Sandbox Code Playgroud)
是相同的 :
Array.prototype.slice.apply(arguments);
Run Code Online (Sandbox Code Playgroud)
如果没有,第一行是做什么的?
Aad*_*hah 10
好吧,让我们通过替换来解决这个问题.我们从:
Function.prototype.call.apply(Array.prototype.slice, arguments);
Run Code Online (Sandbox Code Playgroud)
我们所知道的:
Function.prototype.call
是一个功能.this
指针call
指向Function.prototype
.apply
改变this
指针call
来Array.prototype.slice
.arguments
被施加(未作为参数传递)到call
.因此,上述陈述相当于:
Array.prototype.slice.call(arguments[0], arguments[1], ...);
Run Code Online (Sandbox Code Playgroud)
由此我们看到:
Array.prototype.slice
是一个功能.this
指针slice
指向Array.prototype
.call
改变this
指针slice
来arguments[0]
.arguments[1], ...
作为参数传递给slice
.这与:
arguments[0].slice(arguments[1], ...);
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,我们正在创建一个快速绑定包装了slice
在一个单一的线.
编辑:创建快速未绑定包装器的更好方法如下(请注意,它可能在某些较旧的浏览器中不起作用,但您现在不需要担心 - 您可能总是使用垫片而不是支持bind
):
var slice = Function.prototype.call.bind(Array.prototype.slice);
Run Code Online (Sandbox Code Playgroud)
这与:
function slice() {
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
Run Code Online (Sandbox Code Playgroud)
这个怎么运作:
Function.prototype.call
是一个功能.this
指针call
指向Function.prototype
.bind
改变this
指针call
来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);
Run Code Online (Sandbox Code Playgroud)
call
或apply
.classOf
获取[[Class]]
值的内部.ownPropertyOf
在里面使用in循环.concatenate
连接数组.arrayFrom
创建数组.