Use of the JavaScript ‘bind’ method

Use of the JavaScript ‘bind’ method

What is the use of bind() in JavaScript?

Solutions/Answers:

Solution 1:

Bind creates a new function that will have this set to the first parameter passed to bind().

Here’s an example that shows how to use bind to pass a member method around that has the correct this:

var Button = function(content) { 
  this.content = content;
};
Button.prototype.click = function() {
  console.log(this.content + ' clicked');
};

var myButton = new Button('OK');
myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

Which prints out:

OK clicked
undefined clicked
OK clicked

You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));

Which prints out:

15

Check out JavaScript Function bind for more info and interactive examples.

Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:

Button.prototype.hookEvent(element) {
  // Use bind() to ensure 'this' is the 'this' inside click()
  element.addEventListener('click', this.click.bind(this));
};

Or:

Button.prototype.hookEvent(element) {
  // Use a new variable for 'this' since 'this' inside the function
  // will not be the 'this' inside hookEvent()
  var me = this;
  element.addEventListener('click', function() { me.click() });
}

Or:

Button.prototype.hookEvent(element) {
  // => functions do not change 'this', so you can use it directly
  element.addEventListener('click', () => this.click());
}

Solution 2:

The simplest use of bind() is to make a function that, no matter
how it is called, is called with a particular this value.

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Please refer this link for more information

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Solution 3:

bind allows-

  • set the value of “this” to an specific object. This becomes very helpful as sometimes this is not what is intended.
  • reuse methods
  • curry a function

For example, you have a function to deduct monthly club fees

function getMonthlyFee(fee){
  var remaining = this.total - fee;
  this.total = remaining;
  return this.name +' remaining balance:'+remaining;
}

Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.

Let’s imagine Rachel has a balance of 500, and a monthly membership fee of 90.

var rachel = {name:'Rachel Green', total:500};

Now, create a function that can be used again and again to deduct the fee from her account every month

//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320

Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25

var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200

Solution 4:

From the MDN docs on Function.prototype.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.

So, what does that mean?!

Well, let’s take a function that looks like this :

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let’s take an object that looks like this :

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, we can run Obj.log anywhere in our code :

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of this to our object Obj.


Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

Solution 5:

Variables has local and global scopes. Let’s suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

   var x = 9;    // this refers to global "window" object here in the browser
var person = {
  x: 81,
  getX: function() { return this.x; }
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).

var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).

document.getElementById("demo1").innerHTML = y(); 
document.getElementById("demo2").innerHTML = x2(); 
<!DOCTYPE html>
<html>
<body>
<p id="demo1">0</p>
<p id="demo2">0</p>
</body>
</html>

Solution 6:

I will explain bind theoretically as well as practically

bind in javascript is a method — Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the ‘this’ refers to the first parameter passed to the bind method. Its syntax is

     var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);

Example:–

  var checkRange = function(value){
      if(typeof value !== "number"){
              return false;
      }
      else {
         return value >= this.minimum && value <= this.maximum;
      }
  }

  var range = {minimum:10,maximum:20};

  var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
  var result = boundedFunc(15); //passing value
  console.log(result) // will give true;