In this article, I’ll cover the bind method in Javascript.

The bind method creates a new function that, when called, has this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

To learn more about this keyword, check out this article:

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

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

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

A common mistake for new Javascript programmers is to extract the method from an object, then later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).

Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

this.x = 9;    // 'this' refers to global 'window' object here in a browser
const module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX();
//  returns 81

const retrieveX = module.getX;
retrieveX();
//  returns 9; the function gets invoked at the global scope

//  Create a new function with 'this' bound to module
//  New programmers might confuse the
//  global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
boundGetX(); 
//  returns 81

And that’s it for this article, I hope you enjoyed and learned a lot.

Avatar photo
👋 Hey, I'm Osman Armut
Hi, I'm Osman Armut. I'm a self taught frontend developer that has a great passion for Javascript and React ecosystem. I use articles in my personal learning journey and I like to share my knowledge to help people.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.