DEV Community

amanbhoria
amanbhoria

Posted on

The chronicles of bind method

Taken image matching image to the context

If you know the bind function then it's okay and if you don't know then thank you for not knowing it because that's how you came to this blog. And there's nothing to worry about, I'm here to explain you in the best way possible.

Let's take an example:

Suppose you've an object method inside person object i.e. fullName **and an object i.e **member

const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Aman",
  lastName: "Bhoria",
}
Enter fullscreen mode Exit fullscreen mode

if you want to call the fullName method on the behalf of member object. Here comes the bind method and the syntax as follows:

person.fullName.bind(member);
Enter fullscreen mode Exit fullscreen mode

Bind method will return an function which will be called later. What it does is bind the function to the given object so that function can used that object's properties (if exists)

let result = person.fullName.bind(member);
result (); // Aman Bhoria
Enter fullscreen mode Exit fullscreen mode

Bind method can also be given more than one parameter. The one of course should be the object itself, the rest of them can be the values that we wanna use in the function that is being called.

function fullName (city, country) {
    return this.firstName + " " + this.lastName;
  }

let result = fullName.bind(member, "New Delhi", "India");
result (); // Aman bhoria New Delhi India

Enter fullscreen mode Exit fullscreen mode

You can also give the parameter in the result variable itself

let result = fullName.bind(member);
result("New Delhi", "India"); // Aman bhoria New Delhi India
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion
As you have learned how the _bind _ method works. Get the f**k out of here and use this method wherever you want to.

Keep building!

Top comments (0)