When would you use the bind function in javascript?

Learn how to create object-bound functions in JavaScript

Original Photo by Markus Spiske. Edited by author

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

Image by author

But there’s a way to overcome this restriction.

You can use call(), apply(), and bind() methods to tie a function into an object and call the function as if it belonged to that object.

Image by author

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

Call() Method in JavaScript

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:

var obj = { num: 2 };function add(a){
return this.num + a;
}

Now, there’s a problem with add(). It’s trying to return this.num + some value. But there is no property num inside the function. Thus calling this.num fails.

But as you can see, the object obj has a property num. What if you could call the function add() on that object as if it belonged to the object?

This is indeed possible. To do this, use the call() method to tie the function add() momentarily to the object obj:

add.call(obj, 3);
  • Now the function add() gets its this from obj where it’s bound to.
  • When the add() function is called this.num refers to the num of the obj.
  • Thus the call returns 5 because 2 + 3 = 5.

Use Call() with Multiple Arguments

You can also use call() with functions that accept multiple arguments.

For example:

Output:

10

Apply() Method in JavaScript

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.

For example:

Output:

10

Bind() Method in JavaScript

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():

So calling add.bind(obj, 3, 5) returns a function. In this case, you assign it to a constant called func and then run it.

Calling func() here means calling add() function on the object obj with the arguments of 3, 5.

Now you understand what call(), apply(), and bind() are and how they work. Here’s a summary of how you can use each with the same object-function setup you saw earlier.

Output:

10 10 10

When Use Call() in JavaScript

Let’s have a look at examples of how might want to use call() method in real life.

Use Call() to Chain Object Constructors

For example, let’s create an Item object. The constructor of the Item is defined with name and price.

Let’s also create Car and Fruit objects that are Items. Now, instead of initializing these the same way as Item, you can use the Item object to initialize them. This happens via call() method:

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:

Output:

Position 0: Matt
Position 1: Jack

Use Call() to Run a Function with an Object

You already saw one example of this when defining call().

You can tie a function into an object via call() method. This way you can call the function as if it belonged to the object:

When Use Apply() in JavaScript

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:

const numbers = [1, 2, 3];
const moreNumbers = [4, 5, 6];
numbers.push.apply(numbers, moreNumbers);
console.log(numbers);

Output:

[1,2,3,4,5,6]

Use Apply() to Chain Object Constructors

Similar to using call() to chain constructors, you can chain object constructors with apply(). This time you pass an array of details into the object constructor to initialize the object.

When Use Bind in JavaScript

Create Bound Functions with Bind()

You can use bind() to create a function bound to an object. This way no matter when and how it’s called, it’s called with the object it is tied to.

An example from earlier does exactly this.

Use Bind() to Make SetTimeout Work

This piece of code has an issue:

It does not print the name “John”. Instead, it prints undefined.

To understand why this happens, let’s re-write the last line in another equivalent way:

let func = person.getName;
window.setTimeout(func, 1000);

When window calls its setTimeout() method, its this object is the window object. Thus, when setTimeout() calls the func, which refers to person.getName(), it has no idea what the name of the person was. To overcome this, bind the function to the person object using the bind() method. This way no matter where you call the function, it has still access to the name of the person.

let func = person.getName.bind(person);
setTimeout(func, 1000);

Output:

John

This works because now

  • The person.getName method is assigned to a function func that is bound to the person object.
  • The func has now it's this pointing to the person object. When you pass the bound function into setTimeout(), func still knows how to get the name of the person.

Conclusion

In JavaScript, you can use call(), apply(), and bind() methods to couple a function with an object. This way you can call the function on the object as if it belonged to it.

  • The call() and apply() are very similar methods. They both execute the bound function on the object immediately.
  • The bind() method does not execute the function right away. Instead, it creates and returns a bound function that can be executed later.

This example summarizes using these methods:

Thanks for reading. I hope you enjoy it. Happy coding!

P.S.: Make sure to get my new posts in your inbox. Do that here! Also, to read more world-class stories on Medium, consider becoming a member. It only costs $5 per month. In addition, can make money with your writing too. When I started, I made $5,000 in the first 6 months with programming articles. By signing up with this link, you’ll support me with a portion of your fee, at no extra cost to you. If you do so, thank you so much!

Resources

When would you use the bind function?

The bind() method creates a new function where this keyword refers to the parameter in the parenthesis in the above case geeks. This way the bind() method enables calling a function with a specified this value. Example 4: In this example there is 3 objects, and each time we call each object by using bind()method.

What does bind () do in JavaScript?

bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What is the point of bind?

A bind point refers to a place in a video game where a character will be sent to after using a particular item. Depending on the video game, the bind point is a specific building, a boat, a particular landmark or a specific set of coordinates.

What is the use of BIND In react JS?

The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component.

Postingan terbaru

LIHAT SEMUA