以 this 作为参数的 this.apply 方法 [英] this.apply method with this as parameter

查看:53
本文介绍了以 this 作为参数的 this.apply 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Douglas Crockford 的书 The Good Parts 中,他以这种方式实现了数组推送方法:

On Douglas Crockford's book The Good Parts, he implements the array push method on this way:

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

不明白这是怎么回事.method_name.apply以自身(this)为参数,在代码中对应this.splice.apply;如果我使用 Array.prototype.splice.apply 我没有得到正确的结果.

Dont get it how works this.method_name.apply with itself (this) as parameter, in the code corresponds to this.splice.apply; if I use Array.prototype.splice.apply I don't get the correct result.

希望有人能解释一下 this.splice.apply(this, parameters)Array.prototype.splice.apply(this, parameters) 之间的区别>

Hope somebody may explain me which is the difference here between this.splice.apply(this, parameters) and Array.prototype.splice.apply(this, parameters)

推荐答案

short answer: this.splice.applyArray.prototype.splice 是完全相同的功能.唯一"的区别是使用函数的上下文.this.splice 使用数组的实例作为 this 的值,Array.prototype.splice 使用 Array.prototype 作为 this 的值,这就是为什么在后一种情况下需要使用 .apply 调用它的原因.这样,您就可以告诉函数在运行时将什么用作 this.

short answer: this.splice.apply and Array.prototype.splice are the same exact function. The "only" difference is the context in which the function is used. this.splice uses the instance of your array as the value for this and Array.prototype.splice uses Array.prototype as the value for this which is why you need to invoke it with .apply in the latter case. This way, you're telling the function what to use as this when it's run.

丑陋的事实:在函数定义中this 并没有引用对象Array.prototype,而是this 引用了对象(在本例中是一个数组),它是 Array 的一个 instance.因为对象是Array 的一个实例,意味着它继承了Array.prototype 上定义的所有属性.Array.prototype.slice 定义在 Array.prototype 上,因此它是对象的实例方法,因此您可以使用 this.slice 调用它>.当您以这种方式调用 slice 时,this 指的是您的对象,它又是一个数组.当您使用 Array.prototype.slice 引用切片时,this 在此上下文中引用 Array.prototype,这就是您需要调用的原因它带有 .apply(arguments) 表示运行此函数并使用 this=arguments".

the ugly truth: inside the function definition this does not refer to the object Array.prototype, but instead this refers to the object (in this case an array) which is an instance of Array. Because the object is an instance of Array, means that it inherits all properties defined on Array.prototype. Array.prototype.slice is defined on Array.prototype and so it's an instance method of your object, therefore you can invoke it using this.slice. When you call slice in this manner, this refers to your object, which again is an array. When you refer to slice with Array.prototype.slice then this refers to Array.prototype in this context, which is why you need to invoke it with .apply(arguments) which says "run this function and use this=arguments".

这篇关于以 this 作为参数的 this.apply 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆