Using call and apply
apply methods are other ways of calling a function. They are both similar but there is a minor difference between them, the call function takes a list of arguments and apply takes a single array to pass as arguments.
The first parameter can be different this object. For instance a function which belongs to objectA but you want to use its functionality in objectB. Instead of duplicating the functionality you can use the call method and pass in objectB for it to get that functionality.
With apply you can pass arguments from one function to another or generate an array of values to pass. These features are great tools to help us reuse functionality.
Arguments and converting to an array
arguments object is array-like and stores a collection of passed parameters in the function. You can loop through it as normal to access the values and you can modify them.
This is not a good idea to do but it’s just to demonstrate the point. The only other available property is
length otherwise there is no other properties or methods like
push() on the arguments object. If you want to have access to normal array features then you can convert it to an array like so.
This is one way but
Find the object type
The simple way of working out what type you are dealing with you can use
typeof but you might get results you don’t expect. Follow this link to read more about the
typeof operator and the values it returns.
Using some of what we have learned so far we can figure out better results. We can create our own
typeOf function by using the call method on the object toString method. This string contains the actual type of the object and we extract that out using a regular expression. Which is then converted to lowercase.
You can now pass an array in this function and instead of getting object as the value you will get array. Same with null. This is very useful if you need to know the actual type.
Extending functionality to built in objects
If you come from a c# background you might like to have the
string.format function. So how can you have a format method available for all strings? Simple you can add a format function to the
String.prototype. This principle can be applied to the other global objects like Array, Function, Object and the others.
Hope you will have a use for these snippets of code in your next app. Happy hacking.