javascript ant

RSS or Atom

 

Piles of javascript goodness
 

Apply Method Plus

 

There are a couple of identified patterns for invoking a function. One of which is to use the function method apply() or call() to invoke a function as if it were a method of some other object. This is typically why we might use these methods. However, the apply() method has another handy use. Unlike the call() method the second parameter of the apply() method expects an array. Now, in the context of a function how might we use this to our advantage? Examine the following function that could potentially be used to join several strings together to form a sentence.

This gets the job done, but it could actually be done faster, and with core functions. By using the apply() method and the built in concat() string method, we can improve upon the previous code. Have a look at the new function below that uses apply() and concat().

What I have done here is invoked the concat() string method using apply() so that I can directly pass the arguments array as parameters to the concat() method. I can't directly pass an array to concat(), so by using apply() I allow it to convert my arguments array to parameters. Using the arguments array can be extremely helpful, especially when we need a way to take the arguments array and turn them back into function parameters.