Reputation: 10021
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:
or other advantages I haven't thought of
Upvotes: 0
Views: 27
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