JavaScript(JS) function method - bind

w‮‬ww.theitroad.com

The bind() method is a built-in function method in JavaScript that allows you to bind the this keyword to a specific object and return a new function with the bound this value.

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.

Here's an example:

const obj = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = obj.getX;
console.log(unboundGetX()); // Output: undefined

const boundGetX = unboundGetX.bind(obj);
console.log(boundGetX()); // Output: 42

In this example, the getX() method returns the value of x property in the object obj. However, when the getX() method is assigned to the unboundGetX variable, and then called, the this keyword is no longer referring to obj and returns undefined. To solve this problem, we can use the bind() method to bind the this keyword to the obj object, which will return a new function that always uses obj as its this value, no matter how it's called.

We create a new function boundGetX that is a copy of unboundGetX, but with its this keyword bound to the obj object using the bind() method. When we call boundGetX(), it returns the correct value of the x property in the obj object, which is 42.

The bind() method also allows you to pass in additional arguments that will be appended to the arguments list when the new function is called. For example:

function addNumbers(a, b) {
  return a + b + this.c;
}

const obj = {c: 5};

const boundAddNumbers = addNumbers.bind(obj, 2, 3);
console.log(boundAddNumbers()); // Output: 10

In this example, we define a function addNumbers() that takes two parameters a and b, and returns their sum plus the value of this.c. We then create an object obj with a c property set to 5. We use the bind() method to bind the this keyword to obj and pass in 2 and 3 as additional arguments to addNumbers(). This creates a new function boundAddNumbers that, when called, will add 2, 3, and 5 (the value of c in obj) and return 10.