Vanmeeganathan

Vanmeeganathan

bind() function in Javascript

Vanmeeganathan P K's photo
Vanmeeganathan P K

Published on Feb 6, 2021

3 min read

  • function.prototype.bind() accepts an Object.
  • It binds the calling function to the passed Object and the returns the same.
  • When an object is bound to a function, it means you will be able to access the values of that object from within the function using 'this' keyword.
  • It can also be said as,

function.prototype.bind() is used to provide/change the context of a function.

let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<= this.power; i++) {
      product*=number;
  }
  return product;
}


let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));

let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));

let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));

Let us try to understand this.

let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<= this.power; i++) {
      product*=number;
  }
  return product;
}

Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.

Let us create a function powerOfTwo which will find the second power of a number using the above function.

let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));

Here the object {power : 2} is passed to powerOfNumber function using bind.

The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,

let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<=2; i++) {
      product*=number;
  }
  return product;
}

Hence, powerOfTwo will find the second power.

Similarly, powerOfNumber bound to {power : 3} object will return function finding the third power.

let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<=3; i++) {
      product*=number;
  }
  return product;
}

The powerOfNumber function along with bind() can be used to create different functions to find different powers.

This has wide variety of use cases !

Try Out :

Create an action() function which accepts an action like "run", "walk" etc. Bind the function to a user object with user details.

Now create a function actionForRaj, which is bound to Raj user. On passing an action "Run" to actionForRaj, it should alert a message saying

Raj is running.

Similarly, you can create functions for different users and try calling them with actions.

Happy coding !

 
Share this