Abdul Ahmad
Abdul Ahmad

Reputation: 10021

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. 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

Upvotes: 0

Views: 27

Answers (1)

trincot
trincot

Reputation: 350147

The first (using apply to set this) is a bit more obscure. If one looks just at the function definition, one will spend some time wondering what this is supposed to be. 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.

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.

As a side note: apply allows (and expects) the (other) arguments to be passed as an array. This used to be a "plus" in some scenarios, but has become less significant now that the spread syntax is available.

Upvotes: 1

Related Questions