Skip to content Skip to sidebar Skip to footer

Why Use Apply Method

I read something about the global apply method but I don't understand why I should use the apply method? Can you write to me some examples?

Solution 1:

You use .apply when you want to call a function that takes a variable number of arguments and you don't know in advance how many you will be supplying. So instead, you put those arguments into an array and call the function thus:

myfunc.apply(context, array);

which is equivalent to

myfunc(array[0], array[1], ...);

with this set equal to the context variable.

Solution 2:

Look at MDN there is a very good description (with examples) of apply():

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

Post a Comment for "Why Use Apply Method"