this.apply 以此为参数的方法

this.apply method with this as parameter

在Douglas Crockford的书The Good Parts中,他是这样实现数组push方法的:

Array.prototype.push = function ( ) {
  this.splice.apply(
    this,
    [ this.length, 0 ].
      concat(Array.prototype.slice.apply(arguments))
  );
  return this.length;
};

不明白它是如何工作的。method_name。在代码中应用自身 (this) 作为参数对应于this.splice.apply;如果我使用 Array.prototype.splice.apply 我得不到正确的结果。

希望有人能给我解释一下 this.splice.apply(this, parameters)Array.prototype.splice.apply(this, parameters)

之间的区别

简答:this.splice.applyArray.prototype.splice 是完全相同的函数。 "only" 区别在于使用该函数的上下文。 this.splice 使用数组的实例作为 this 的值,Array.prototype.splice 使用 Array.prototype 作为 this 的值,这就是为什么你需要调用它的原因.apply 在后一种情况下。这样,您就可以告诉函数在 运行.

时使用什么作为 this

丑陋的事实:在函数定义中 this 不引用对象 Array.prototype,而是 this 引用对象(在本例中为数组),它是Array 实例 。因为该对象是 Array 的实例,意味着它继承了 Array.prototype 上定义的所有属性。 Array.prototype.slice 是在 Array.prototype 上定义的,因此它是对象的实例方法,因此您可以使用 this.slice 调用它。当您以这种方式调用 slice 时,this 指的是您的对象,它又是一个数组。当您使用 Array.prototype.slice 引用 slice 时,那么 this 在此上下文中引用 Array.prototype,这就是为什么您需要使用 .apply(arguments) 调用它,即 "run this function and use this=arguments"。