With the bind() method, an object can borrow a method from
another object. Unlike call() and apply(), which invoke the
function immediately, bind() creates a new function that can
be executed later.
Here, the person object has a method, and we use bind() to create
a new function that is permanently linked to member.
const person = {
firstName: "Mim",
lastName: "Akter",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName: "Redo",
lastName: "Hub"
}
let fullName = person.fullName.bind(member);
console.log(fullName()); // "Redo Hub"
The most common use case for bind() is when you want a function to keep its
this value, even if it is passed as a callback.
When a method is passed as a callback (e.g., in a setTimeout), the
context is lost. this becomes the global object or
undefined.
const person = {
firstName: "Mim",
sayHi: function () {
console.log("Hi " + this.firstName);
}
}
// Without bind, "this" is lost after 1 second
setTimeout(person.sayHi, 1000); // Output: "Hi undefined"
// With bind, "this" is preserved
let boundHi = person.sayHi.bind(person);
setTimeout(boundHi, 1000); // Output: "Hi Mim"
bind() creates a new function (it doesn't
execute it immediately)this context to a
specific objectcall() and
apply() which run the function right awaybind() because they inherit
this from their parent scope