Eastern Monk
Eastern Monk

Reputation: 6635

Javascript: When should I use function_name.apply ?

Many times I see statements like following

 Y.CustomApp.superclass.render.apply(this, arguments);

I know how apply works. As per MDN

Calls a function with a given this value and arguments provided as an array.

But then why not call the method directly ?

Upvotes: 3

Views: 83

Answers (2)

Guffa
Guffa

Reputation: 700292

You use apply when the function is not a method in the object.

Example:

var obj = { firstName: 'John', lastName: 'Doe' }

function getName() {
  return this.firstName + ' ' + this.lastName;
}

var name = getName.apply(obj);

Upvotes: 2

Pointy
Pointy

Reputation: 413720

The reasons you use apply() are one or both of:

  • You've got the arguments to be passed to the function in the form of an array or array-like object already;
  • You want to ensure that this is bound in some particular way when the function is invoked.

If you've got a list of values in an array for some reason, and you know that those values are exactly what to pass to the function, what else would you do? Something like:

if (array.length == 1)
  theFunction(array[0]);
else if (array.length == 2)
  theFunction(array[0], array[1]);
else ...

clearly is terrible.

If you know that you want this to be bound to some object, well you could always make the function a temporary property of the object and call the function via the object, but that's also pretty terrible. If all you need to do is bind this, and the arguments aren't in an array, well your alternative is to use .call() instead of .apply().

Upvotes: 3

Related Questions