JavaScript bind() Function

JavaScript bind() Function | Here we will discuss what is bind() function in JavaScript. Using the bind() function, JavaScript function binding is accomplished. This technique allows us to associate an object with a generic function, which, when called, will return a different result. Otherwise, the function executes with the same outcome or generates an error.

To invoke a function using this value, which relates to the same object that is now selected, we utilize the bind() method. In other words, the bind() approach makes it simple to provide the object to which this keyword will be bound when a function or method is called. When we use this keyword in a method and call that method from a receiver object, the need for binding typically arises because sometimes this is not bound to the entity we expect it to be bound to. This causes issues with our program. Also see:- Dynamic Variable Name in JavaScript

Syntax of Bind Function in JavaScript:-
function.bind(thisArg [, arg1[, arg2[, …] ] ]

Let’s see a few examples to understand the JavaScript bind() function in a better way.

var website = {
  name: "Know Program",
  getName: function () {
    return this.name;
  },
};

var unboundGetName = website.getName;
var boundGetName = unboundGetName.bind(website);
console.log(boundGetName());

Output:-

Know Program

Example 2: JavaScript bind() Function

// Here, this refers to the global "window" object
this.name = "Google";
var website = {
  name: "Know Program",
  getName: function () {
    return this.name;
  },
};

console.log(website.getName());

// it invokes at global scope
var retrieveName = website.getName;
console.log(retrieveName());

var boundGetName = retrieveName.bind(website);
console.log(boundGetName());

Output:-

Know Program
Google
Know Program

The JavaScript Function bind() technique can create a new function. A function’s own this keyword is set to the supplied value and receives the specified number of arguments when it is called.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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