在javascript中调用并应用

hgu*_*ser 2 javascript

可能重复:
链接呼叫和一起应用的含义是什么?

我发现了一些这样的代码:

function fun() {
    return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
Run Code Online (Sandbox Code Playgroud)

我知道callapplyjs,但是当他们走到一起时我很困惑.

然后我想知道是否

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)

我们所知道的:

  1. Function.prototype.call 是一个功能.
  2. this指针call指向Function.prototype.
  3. 我们用apply改变this指针callArray.prototype.slice.
  4. arguments施加(未作为参数传递)到call.

因此,上述陈述相当于:

Array.prototype.slice.call(arguments[0], arguments[1], ...);
Run Code Online (Sandbox Code Playgroud)

由此我们看到:

  1. Array.prototype.slice 是一个功能.
  2. this指针slice指向Array.prototype.
  3. 我们用call改变this指针slicearguments[0].
  4. 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)

这个怎么运作:

  1. Function.prototype.call 是一个功能.
  2. this指针call指向Function.prototype.
  3. 我们用bind改变this指针callArray.prototype.slice.
  4. 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)
  1. 使用这个你可以使用任何轻松地创建结合的包装callapply.
  2. 您可以使用classOf获取[[Class]]值的内部.
  3. 你可以ownPropertyOf在里面使用in循环.
  4. 您可以使用concatenate连接数组.
  5. 您可以使用arrayFrom创建数组.