Bind(), Call() and Apply()
Right time to use in Javascript

Bind(), Call() and Apply() Right time to use in Javascript

When to use Bind(), Call() and Apply() methods in javascript

Most of the time when working on the project's developer thinks to deal with Bind(), Call() and Apply() methods and when to use them in projects, let's try to understand them in detail and find out what is the right time to use which method. so let's begin.

1. Traditionally in JavaScript

you can have objects that have their own properties and methods. For example, objects cannot use the methods of object2 and vice versa.

1.jfif

1b.jpg

Let's go through these three methods one by one and see some use-cases as well.

2. Call() Method

The call() method invokes a function with a specified context. In other words, you can tie a function into an object as if it belonged to the object.

Example Let's create an object obj and a function add() for adding up a number with another:

2.jfif

3. Apply() Method

The apply() method does the exact same as call(). The difference is that call() accepts an argument list, but apply() accepts an array of arguments.

Example

3.jfif

4. Bind() Method

You previously learned what call() and apply() methods do. As you saw, they executed the function immediately when called (and returned a value).

The bind() method is reminiscent of call() and apply(). But instead of executing a function immediately, bind() returns a function that can be executed later on.

Let's modify the previous example to use bind():

4.jfif

5. Using bind()

To borrow methods from a different object

Example

7.jfif

6. Use Call()

To Invoke an Anonymous Function Let's create an anonymous function and use call() to invoke it for each object of an array.

The anonymous function adds a displayinfo() function for each array object. This is to make it print the correct position of each person in the queue:

5.jfif

7. Use Apply()

To Append an Array to Another Array You can use push() method to append elements into an array.

If you pass an array to push() method, it will add the whole array as a single element into the array. This means you have an array inside an array. Here you can use concat(but it creates a new array.

If you want to append an array as a whole into an existing array, use apply().

For example:

6.jfif

Summary

call, apply, and bind are the functions that help you change the context of the this keyword present inside the invoking function.

• We saw how each function can be called in different ways - for example,

with apply you can execute a function with an array of arguments, and

with the call function you can execute the same but the arguments are spread via commas.