Apply, Call and Bind

Swathi Bhat
3 min readOct 2, 2021

--

The 3 most commonly used built-in methods for JavaScript functions — apply, bind and call. These are used when invoking a function. The methods “apply” and “call” invoke the functions immediately while “bind” prepares the function for later invocation.

Apply:

The ‘apply’ method invokes the function with the context that is passed along with the arguments. This allows the user to alter the context from the scope available to the function to the scope the user intends to be available to the function. Also, the function is called immediately after context setting.

The context within the function ‘foo’ is the passed value of this. The function foo obtains the data or context provided through ‘this’ parameter. The arguments are sent as an array and not separately. This is useful when you need data or information to complete the tasks but they are pertaining to a context or object. Like computing tasks for a particular person’s information.

Bind:

The ‘bind’ method is used when the function needs to be bound to a specific context but not immediately invoked. It allows the user to specify the ‘this’ context pertaining to the function regardless of where the function is called and defined.

The function context will be the object, no matter where the function is invoked. It sets the context but not invoked immediately. You want certain set of actions to have a preset amount of information while computing. Like when you want to have a person’s data for performing certain tasks. You bind the function containing those tasks to the context containing the person’s information. Like in the above scenario, you bind ‘foo’ to ‘object’.

Call:

In this method, the context is passed along with invoking the function. It allows the user to set the context for the function the same way as ‘apply’, the difference being, the arguments are sent separately rather than in an array. The function is invoked immediately after setting the context.

The function context will be the object. And the argumentsList is not sent as an array, but separately. It is useful when you want to perform tasks pertaining to one object with reference to the second object; in places where the second object must be taken as context for a method, but the method cannot be duplicated with respect to the second object.

--

--

Swathi Bhat
Swathi Bhat

Written by Swathi Bhat

A software developer based out of Bangalore, who loves to talk about JavaScript!

No responses yet