Javascript Function Bind
The bind()
method in JavaScript creates a new function with a specified this value and optionally some pre-set arguments.
It returns a new function that, when called, has the this keyword set to the provided value, with a given sequence of arguments preceding any other arguments provided when the new function is called.
Here's an example of how to use bind()
:
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const greet = function (message) {
console.log(message + ", " + this.fullName());
};
const greetJohn = greet.bind(person, "Hello");
greetJohn(); // "Hello, John Doe"
In this example:
- We have an object person with two properties firstName and lastName, and a method
fullName()
that returns the full name of the person. - We also have a function
greet()
that takes a message as an argument and logs a greeting message that includes the full name of the person. - We create a new function greetJohn by calling
bind()
on thegreet()
function and passing the person object as the first argument, followed by the message "Hello". - This creates a new function that, when called, logs the message "Hello, John Doe".
- We then call
greetJohn()
, which logs the message using thefullName()
method of the person object.
tip
The bind()
method is useful when you want to create a new function that has a fixed this value and some pre-set arguments. It allows you to reuse a function with different this values or argument sequences without having to redefine the function.
Difference between bind()
, call()
, and apply()
The bind()
method is similar to the call()
and apply()
methods, but there are some differences:
bind() | call() | apply() |
---|---|---|
Creates a new function with a specified this value and arguments provided one by one. | Calls a function with a specified this value and arguments provided one by one. | Calls a function with a specified this value and arguments provided as an array (or an array-like object). |
Returns a new function. | Returns the result of the function. | Returns the result of the function. |
Does not immediately execute the function. | Immediately executes the function. | Immediately executes the function. |