๐ง What is bind()
and Why Is It Used?
The bind()
method in JavaScript is used to create a new function with a permanently bound this
value. It’s especially useful when a method loses its original context — like when passed as a callback or event handler.
๐ฏ Real-Time Example with Explanation
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const member = {
firstName: "New",
lastName: "Person",
};
let fullName = person.fullName.bind(member);
console.log(fullName());
Explanation:
person.fullName
is a method that returns the full name using its ownthis
.- To use this method for another object (
member
), we bind it. - Now
this
points tomember
instead ofperson
. - The result is
"New Person"
.
❗ Multi-bind Example: What Happens?
function name() {
console.log(this.name);
}
name = name.bind({ name: "" }).bind({ name: "Doe" }).bind({ name: "Third" });
name();
Expected output:
Third
Actual output:
(empty string)
๐ง Explanation
The first bind()
fixes the context of this
to { name: "" }
. All later bind()
calls are ignored.
Once a function is bound, you cannot rebind it.
Only the first call tobind()
matters.
✅ Key Takeaways
bind()
returns a new function with a lockedthis
.- You can’t change the context after the first
bind()
. - If you want a different binding, start with the unbound original function.
- Use
.call()
or.apply()
if you want to set context dynamically at call time.
๐งช Final Output Recap
name = name.bind({ name: "" }).bind({ name: "Doe" }).bind({ name: "Third" });
name(); // Output: (empty string)
๐ก Pro Tip
Never bind a function more than once. Save the original if you plan to reuse or change the context. Also remember, bind()
has no effect on arrow functions since they don’t have their own this
.
Comments
Post a Comment