Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why invoke "apply" instead of calling function directly?

When looking at the source code for raphael or g.raphael or other libraries I've noticed the developer does something like this:

var val = Math.max.apply(Math, data_array);

Why not just invoke the function directly, such as:

var val = Math.max(data_array);

Thanks.

like image 403
codecraig Avatar asked May 09 '11 12:05

codecraig


People also ask

What is the difference between call () and apply () methods?

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.

Is calling and invoking a function is same?

There is a very slight difference between calling and invoking a function. In JavaScript functions can be invoked without being called which means that the code inside the body of the function can be executed without creating an object for the same.

What is the difference between call bind and apply?

Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.

Why do we use call and apply?

call and apply are very similar—they invoke a function with a specified this context, and optional arguments. The only difference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.


1 Answers

Math.max won't accept a list by default. "apply" allows you to unpack the list to arguments so that max works correctly.

like image 85
Juho Vepsäläinen Avatar answered Nov 06 '22 10:11

Juho Vepsäläinen