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.
Math.max won't accept a list by default. "apply" allows you to unpack the list to arguments so that max works correctly.
Generally you would use
apply()
andcall()
to be able to set the context or the object to which the calling function belongs to. The function then effectively becomes a method of that object/context which is helpful if you'll need to access the fields of the context.This is how Javascript natively invokes functions:
Reference: Understanding JavaScript Function Invocation and "this" by Yehuda Katz
So, when calling a function directly you are actually implicitly passing in a default context to the function. Javascript passes
'window'
or'undefined'
as context when you don't specify it usingcall()
orapply()
This answer also gives an example which might help in understanding the usage
Why invoke “apply” instead of calling function directly? Let's have a snippet:
Here we can see we are using
'this'
(context) within a function, If we directly call a func than we don't have any context, than it will takewindow
context, which is wrong. So, if you are using context within your function than useapply
method.I think the explanation from the Mozilla Docs describes it well:
As for the parameters:
The docs give a good example of a use case for apply. In the example below, apply is used to chain a constructor:
Notice that in the
prod_dept
constructor, thethis
supplied refers to theprod_dept
object, andarguments
is an array of arguments passed to theproduct
constructor..apply
is often used when the intention is to invoke a variadic function with a list of argument values, e.g.The
Math.max([value1[,value2, ...]])
function returns the largest of zero or more numbers.The
Math.max()
method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.However, as of the ECMAScript 6 you can use the spread operator:
When calling a function using the variadic operator, you can even add additional values, e.g.