Difference between apply, call and bind method in javascript

Difference between apply, call and bind method in javascript

Javascript provides various ways by which we can invoke a function. Some of the functionalities javascript provides is facilitating the use of apply, call and bind to invoke a function.

All these three are used to invoke a function with a set of parameters. The difference between these types of invocation is the type of parameters supplied to the respective method.

Using call for function invocation: 

Using ‘call’ we can invoke a function by providing object in the parameter. The syntax is :

functionName.call(objectName, parameters of function separated by comma);

Consider the following function:

var hello = function(message)
	console.log(message+' '+this.name+ '!');

If you want to call the above function you need to provide it an object scope from which it can use the value ‘this.name’. This can be done by using the ‘call’ method. Take a look at the below code:

In the above example, we are calling the function ‘hello’ twice, each time providing a different message and a different object from where it gets the data ‘this.name’. The output will be “Hello John!” for the first function call and “Hi Peter!” for the second one.

Consider the second example. Here we are making use of ‘call’ to invoke a function which has 3 parameters. The limitation of using a call method invocation is that you need to know the number of arguments of the invoking function beforehand which kind of makes it a little less flexible.

Using apply for function invocation:

The usage of apply is similar to the above implementation of call. The only difference being instead of passing the function parameters separately comma separated, we pass an array containing all the parameters. Take a look at the below example which is the implementation of the above example using apply


Using bind for function invocation:

Using apply and call were almost similar in its syntax and implementation logic. But bind is different. In apply and call, the function is invoked immediately. Bind on the other hand returns a function. It can be used for currying of functions  which means it allows for partial execution of the function. You can pass the function a set of parameters using the bind method and it will return a function which you can invoke later by optionally providing another set of arguments which will be used for execution.

Take a look at the below example to understand better:

In the above example we are invoking the function using bind by initially supplying the object person and one parameter. The object properties and the parameter are stored in the closure function which is returned by bind. This returned function is then invoked by providing additional remaining parameters. The initially supplied parameters were retained in the closure which was available for the subsequent execution.

Comments are closed.