Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which approach is better: function.apply(<this>, args) or having a function to accept <this> as argument?

Tags:

javascript

Let's say that I have a functionA defined like this:

functionA = function(myObject, someParams) {
  myObject.save_some_data = someParams;
  myObject.processed = true;
}

I can then call it and pass an object to work on as functionA(someObject, someParams).

I can, however, transform this example with apply():

functionA = function(someParams) {
  this.save_some_data = someParams;
  this.processed = true;
}

functionA.apply(someObject, [someParams]);

Both approaches seems to be achieving the same goal, or am I missing something?

But since apply() does exist in JavaScript, what are the benefits of using it instead of having my functions accept this as a first argument?

like image 787
mishik Avatar asked Jun 30 '13 15:06

mishik


People also ask

What is the difference between using call () and apply () to invoke a function with multiple arguments?

The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

What's the notable difference between the function call and function apply methods?

Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function.

How do you write a function that accepts any number of arguments?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.


1 Answers

apply is going to use someParams as an array of arguments; call would actually do the same thing:

functionA.call(someObject, someParams);

There are no benefits except for style. Passing someObject as an argument is probably going to make more sense in most cases, but it’s really up to you and which one you like best.

like image 87
Ry- Avatar answered Oct 27 '22 07:10

Ry-