[javascript] What is the use of the JavaScript 'bind' method?

What is the use of bind() in JavaScript?

This question is related to javascript function bind

The answer is


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


Simple example

function lol(second, third) {
    console.log(this.first, second, third);
}

lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"

lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"

lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"

const newLol = lol.bind({first: '1'}); 
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"

const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"

const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"

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;

Summary:

The bind() method takes an object as an first argument and creates a new function. When the function is invoked the value of this in the function body will be the object which was passed in as an argument in the bind() function.

How does this work in JS anyway

The value of this in javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window (or global in nodeJS). Only call, apply and bind can alter the this binding differently. Here is an example to show how the this keyword works:

_x000D_
_x000D_
let obj = {_x000D_
  prop1: 1,_x000D_
  func: function () { console.log(this); } _x000D_
}_x000D_
_x000D_
obj.func();   // obj left of the dot so this refers to obj_x000D_
_x000D_
const customFunc = obj.func;  // we store the function in the customFunc obj_x000D_
_x000D_
customFunc();  // now the object left of the dot is window, _x000D_
               // customFunc() is shorthand for window.customFunc()_x000D_
               // Therefore window will be logged
_x000D_
_x000D_
_x000D_

How is bind used?

Bind can help in overcoming difficulties with the this keyword by having a fixed object where this will refer to. For example:

_x000D_
_x000D_
var name = 'globalName';_x000D_
_x000D_
const obj = {_x000D_
  name: 'myName',_x000D_
  sayName: function () { console.log(this.name);}_x000D_
}_x000D_
_x000D_
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred_x000D_
_x000D_
say(); // now because this function is executed in global scope this will refer to the global var_x000D_
_x000D_
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object_x000D_
_x000D_
boundSay();  // Now this will refer to the name in the obj object: 'myName'
_x000D_
_x000D_
_x000D_

Once the function is bound to a particular this value we can pass it around and even put it on properties on other objects. The value of this will remain the same.


/**
 * Bind is a method inherited from Function.prototype same like call and apply
 * It basically helps to bind a function to an object's context during initialisation 
 * 
 * */

window.myname = "Jineesh";  
var foo = function(){ 
  return this.myname;
};

//IE < 8 has issues with this, supported in ecmascript 5
var obj = { 
    myname : "John", 
    fn:foo.bind(window)// binds to window object
}; 
console.log( obj.fn() ); // Returns Jineesh

Bind Method

A bind implementation might look something like so:

Function.prototype.bind = function () {
  const self = this;
  const args = [...arguments];
  const context = args.shift();

  return function () {
    return self.apply(context, args.concat([...arguments]));
  };
};

The bind function can take any number of arguments and return a new function.

The new function will call the original function using the JS Function.prototype.apply method.
The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).

An example can look something like so:

_x000D_
_x000D_
function Fruit(emoji) {_x000D_
  this.emoji = emoji;_x000D_
}_x000D_
_x000D_
Fruit.prototype.show = function () {_x000D_
  console.log(this.emoji);_x000D_
};_x000D_
_x000D_
const apple = new Fruit('');_x000D_
const orange = new Fruit('');_x000D_
_x000D_
apple.show();  // _x000D_
orange.show(); // _x000D_
_x000D_
const fruit1 = apple.show;_x000D_
const fruit2 = apple.show.bind();_x000D_
const fruit3 = apple.show.bind(apple);_x000D_
const fruit4 = apple.show.bind(orange);_x000D_
_x000D_
fruit1(); // undefined_x000D_
fruit2(); // undefined_x000D_
fruit3(); // _x000D_
fruit4(); // 
_x000D_
_x000D_
_x000D_


The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.

setInterval(this.animate_to.bind(this), 1000/this.difference);

Creating a new Function by Binding Arguments to Values

The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.

Partial Application

This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.

A Higher Order Function (HOF)

Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.

Binding Multiple Arguments

You can use bind to transform functions with multiple arguments into new functions.

_x000D_
_x000D_
function multiply(x, y) { _x000D_
    return x * y; _x000D_
}_x000D_
_x000D_
let multiplyBy10 = multiply.bind(null, 10);_x000D_
console.log(multiplyBy10(5));
_x000D_
_x000D_
_x000D_

Converting from Instance Method to Static Function

In the most common use case, when called with one argument the bind method will create a new function that has the this value bound to a specific value. In effect this transforms an instance method to a static method.

_x000D_
_x000D_
function Multiplier(factor) { _x000D_
    this.factor = factor;_x000D_
}_x000D_
_x000D_
Multiplier.prototype.multiply = function(x) { _x000D_
    return this.factor * x; _x000D_
}_x000D_
_x000D_
function ApplyFunction(func, value) {_x000D_
    return func(value);_x000D_
}_x000D_
_x000D_
var mul = new Multiplier(5);_x000D_
_x000D_
// Produces garbage (NaN) because multiplying "undefined" by 10_x000D_
console.log(ApplyFunction(mul.multiply, 10));_x000D_
_x000D_
// Produces expected result: 50_x000D_
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
_x000D_
_x000D_
_x000D_

Implementing a Stateful CallBack

The following example shows how using binding of this can enable an object method to act as a callback that can easily update the state of an object.

_x000D_
_x000D_
function ButtonPressedLogger()_x000D_
{_x000D_
   this.count = 0;_x000D_
   this.onPressed = function() {_x000D_
      this.count++;_x000D_
      console.log("pressed a button " + this.count + " times");_x000D_
   }_x000D_
   for (let d of document.getElementsByTagName("button"))_x000D_
      d.onclick = this.onPressed.bind(this);_x000D_
}_x000D_
_x000D_
new ButtonPressedLogger();      
_x000D_
<button>press me</button>_x000D_
<button>no press me</button>
_x000D_
_x000D_
_x000D_


Simple Explanation:

bind() create a new function, a new reference at a function it returns to you.

In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.

You can preconfigure as many parameters as you want.

Simple Example to understand bind:

function calculate(operation) {
  if (operation === 'ADD') {
   alert('The Operation is Addition');
  } else if (operation === 'SUBTRACT') {
   alert('The Operation is Subtraction');
  }
}

addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));


In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.


As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.

A couple of analogous toolkit API methods that perform a similar service:

jQuery.proxy()

Dojo.hitch()


Consider the Simple Program listed below,

//we create object user
let User = { name: 'Justin' };

//a Hello Function is created to Alert the object User 
function Hello() {
  alert(this.name);
}

//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();

//we create an instance to refer the this keyword (this.name);

bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:

_x000D_
_x000D_
    var rateOfInterest='4%';_x000D_
    var axisBank=_x000D_
    {_x000D_
    rateOfInterest:'10%',_x000D_
    getRateOfInterest:function()_x000D_
    {_x000D_
    return this.rateOfInterest;_x000D_
    }_x000D_
    }_x000D_
    axisBank.getRateOfInterest() //'10%' _x000D_
_x000D_
_x000D_
    let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax_x000D_
    knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context_x000D_
_x000D_
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank);     //so here we need bind function call  to its local context_x000D_
_x000D_
_x000D_
    knowExactAxisBankInterest() // '10%' 
_x000D_
_x000D_
_x000D_


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:

_x000D_
_x000D_
var x = 9; // this refers to global "window" object here in the browser_x000D_
var person = {_x000D_
  x: 81,_x000D_
  getX: function() {_x000D_
    return this.x;_x000D_
  }_x000D_
};_x000D_
_x000D_
var y = person.getX; // It will return 9, because it will call global value of x(var x=9)._x000D_
_x000D_
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)._x000D_
_x000D_
document.getElementById("demo1").innerHTML = y();_x000D_
document.getElementById("demo2").innerHTML = x2();
_x000D_
<p id="demo1">0</p>_x000D_
<p id="demo2">0</p>
_x000D_
_x000D_
_x000D_


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

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.


The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

   window.color = "red"; 
   var o = { color: "blue" }; 
   function sayColor(){ 
       alert(this.color); 
   } 
   var objectSayColor = sayColor.bind(o); 
   objectSayColor(); //blue 

Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS


  • 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.

_x000D_
_x000D_
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));
_x000D_
_x000D_
_x000D_

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.

Feel free to check this out.

bind() function in Javascript


i did not read above code but i learn something in simple so want to share here about bind method after bind method we can use it as any normal method.

<pre> note: do not use arrow function it will show error undefined  </pre>

_x000D_
_x000D_
let solarSystem = {
    sun: 'red',
    moon : 'white',
    sunmoon : function(){
       let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
        return dayNight;
    }
}

let work = function(work,sleep){
    console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()
    console.log('i work in '+ work +' and sleep in '+sleep);
}

let outPut = work.bind(solarSystem);
outPut('day','night')
_x000D_
_x000D_
_x000D_


Another usage is that you can pass binded function as an argument to another function which is operating under another execution context.

var name = "sample";
function sample(){
  console.log(this.name);
}
var cb = sample.bind(this);

function somefunction(cb){
  //other code
  cb();
}
somefunction.call({}, cb);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to bind

Docker Error bind: address already in use Update Angular model after setting input value with jQuery How to remove an appended element with Jquery and why bind or live is causing elements to repeat How to enable named/bind/DNS full logging? What does it mean to bind a multicast (UDP) socket? Detect user scroll down or scroll up in jQuery Cannot assign requested address using ServerSocket.socketBind jQuery bind/unbind 'scroll' event on $(window) What is the use of the JavaScript 'bind' method? Understanding ASP.NET Eval() and Bind()