简体   繁体   中英

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 ?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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