In JavaScript, the bind()
method allows you to create a new function with a specific context and preset arguments.
Here’s how it works:
Create new function with a specific context:
Suppose you have an object called person
with a greeting()
method that logs a message to the console:
const person = {
name: "John Doe",
greeting: function () {
console.log(`Hello, my name is ${this.name}!`);
},
};
person.greeting(); // This will output "Hello, my name is John Doe!"
The this
value inside the greeting()
method refers to the person
object.
However, if you were to assign the greeting()
method to a new variable like this:
const greetFunction = person.greeting;
greetFunction(); // This will output "Hello, my name is undefined!"
The output will be undefined
because this
is no longer set to the person
object. Instead, it refers to the global
object or undefined
in strict mode.
To fix this, you can use the bind()
method to create a new function that has the person
object as its this
value:
const boundGreetFunction = person.greeting.bind(person);
boundGreetFunction();
In this example, we have used bind()
to create a new function called boundGreetFunction
that has the person
object as its this
value. When we call boundGreetFunction()
, the output is the expected message with the correct values.
Create a new function with preset arguments:
You can also use bind()
to create a new function with preset arguments. For example, suppose you have a function called sum()
that takes two arguments and returns their sum:
function sum(a, b) {
return a + b;
}
You can use bind()
to create a new function called addTen()
that always adds 10 to its argument:
const addTen = add.bind(null, 10);
console.log(addTen(20)); // This will output 30
In this example, we passed null
as the context argument since we don’t need to specify a context for this function.
The end result of above code is 30
.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.