JavaScript call(), apply() and bind() – when and where to use?


 

 

In JavaScript, call(), apply() and bind() methods are very useful to execute a function in a given context and the arguments.

The call() and apply() methods are almost similar, these methods execute the function immediately with  the given context and the arguments except only one difference. The call() method will accept arguments as comma(,) separated and the apply() method will accept as an array.

The bind() method will not execute the function immediately, instead it will bind the function for the given context, later we can call with the required arguments.

Let’s have an example of finding Google map directions for three places:

  1. Chennai
  2. Ooty
  3. Thanjavur

The corresponding JavaScript objects for these three places are:

 

 

Map function for Direction

The “launchMap” function will simply open the Google map with source, destination and the travel mode.

Using call() method

In this case, I know the source which is “Coimbatore” and the destination is “Chennai” and the travel mode is “driving”.

The above call will open the map for the following URL:

https://www.google.com/maps/dir/?api=1&origin=Coimbatore&destination=Chennai&travelmode=driving

Using apply() method

This is exactly like the call method, but passing arguments as array, let’s use the trip2 data for this.

The above apply() method, will open the following URL:

https://www.google.com/maps/dir/?api=1&origin=Coimbatore&destination=Ooty&travelmode=driving

When to use bind() method?

Well, for the first two options, we know the source as “Coimbatore”, let’s have a scenario, where we need to find the directions for the trip3 place (Madurai)  from user’s current geo location, which we need to collect it in future. In that case, we can simply use the bind() method to bind the “launchMap” function and we can execute it later once the user’s geo location is available.

Let’s use the JavaScript’s navigator object to get user’s current geo position, once it’s available we can call the “callLater” function with the coordinates.

The above code, will launch the direction map between the current user’s geo location and “Madurai”.

Complete Source Code:

 

 

Tags: , ,

You may also like

Sponsored

Follow me

Popular posts