What is Bind Method in JavaScript

In this article we will have a look at the Bind function in JavaScript. This method binds a function to an object. 

Before reading this article, you may want to go through the following articles:

For example if you have a function as in the following:

function FindSquare(number) { 
   
return number * number;
}

And you have created an object as below:

var Calculator = {};

Then as you see, the calculator object does not contain properties or methods. Now let us say you want to bind the function FindSqaure to the object Calculator You can then do that using the Bind method in JavaScript.

  1. The Bind method binds a function to an object
  2. It returns a function after binding

So you can bind the FindSquare function to the Calculator object as in the following:

var CFindSquare = FindSquare.bind(Calculator);

Now when you call the CFindSquare function and pass a parameter, it will actually be passed to the original function FindSquare.
You can invoke the FindSquare method on the object Calculator as in the following:

var result = CFindSquare(8);
alert(result);

In this way you can work with the bind() method in JavaScript. I hope you find this article useful. Thanks for reading. 

Up Next
    Ebook Download
    View all
    Learn
    View all