简体   繁体   English

使用 function.apply(obj) vs function(obj) 有什么好处吗

[英]is there a benefit to using function.apply(obj) vs function(obj)

in javascript we can perform operations on an object in a few different ways.在 javascript 中,我们可以通过几种不同的方式对 object 执行操作。 My question is primarily about the 2 ways described below:我的问题主要是关于以下描述的两种方式:

function op() {
  this.x;
  this.y;
  etc..
}

op.apply(someObject);

or或者

function op(ob) {
  ob.x;
  ob.y;
  etc..
}

op(someObject);

both of these seem to get the same end result.这两个似乎都得到了相同的最终结果。 are there scenarios where using one has advantages over using the other?是否存在使用其中一种比使用另一种具有优势的情况?

advantages can be things that make the code:优点可以是使代码产生的东西:

  1. more flexible更灵活
  2. more declarative更具声明性
  3. easier to maintain更容易维护
  4. simpler更简单

or other advantages I haven't thought of或其他我没有想到的优点

The first (using apply to set this ) is a bit more obscure.第一个(使用apply来设置this )有点模糊。 If one looks just at the function definition, one will spend some time wondering what this is supposed to be.如果只看 function 定义,就会花一些时间想知道this应该是什么。 If by any chance, the function is defined as a method, then naturally one would assume that this is supposed to refer to the object it is defined on.如果有任何机会,function 被定义为一种方法,那么自然会假设this应该是指它所定义的 object。

The second variant (without apply ) is clearer: the parameter has a name that can (should) reveal its role, while this can remain available for when the function is assigned to an object property, and it is called as a method on that object.第二个变体(没有apply )更清楚:参数有一个可以(应该)显示其角色的名称,而当 function 分配给 object 属性时, this仍然可用,并且它被称为 ZA8CFDE6331ACZFB689 上的方法.

As a side note: apply allows (and expects) the (other) arguments to be passed as an array.附带说明: apply允许(并期望)将(其他)arguments 作为数组传递。 This used to be a "plus" in some scenarios, but has become less significant now that the spread syntax is available.在某些情况下,这曾经是一个“加号”,但现在可以使用扩展语法已经变得不那么重要了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM