JavaScript Function bind()
14 April 2025 | Category: JavaScript
The bind()
method in JavaScript is used to create a new function that, when called, has its this
keyword permanently set to a specific value.
Unlike call()
and apply()
, which invoke the function immediately, bind()
returns a new function that you can call later.
✅ Syntax
function.bind(thisArg, arg1, arg2, ...)
Parameters:
thisArg
– The value you wantthis
to refer to.arg1, arg2, ...
– Optional arguments that are prepended to arguments passed when the bound function is called.
🔍 Example: Basic Usage
const person = {
name: "Dev",
};
function greet() {
console.log("Hello, " + this.name);
}
const greetPerson = greet.bind(person);
greetPerson(); // Output: Hello, Dev
Even though
greet()
is a standalone function,bind()
locksthis
to theperson
object.
⚙️ Pre-filling Arguments (Partial Application)
You can also use bind()
to preset some arguments:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
console.log(double(5)); // Output: 10
Here,
a
is fixed as 2, and we just need to passb
.
⏱ Real-World Use Case: Event Handlers
In event handlers, this
often refers to the DOM element. You can use bind()
to attach your own object as this
:
function showMessage() {
alert(this.message);
}
const obj = { message: "Hello from bind!" };
const boundFunc = showMessage.bind(obj);
document.getElementById("btn").addEventListener("click", boundFunc);
❗ Important Notes
Feature | Description |
---|---|
Returns | A new function with this bound permanently |
Not called | bind() does not call the function immediately |
Permanent | Once bound, this can’t be changed by call() or apply() |
🤝 bind()
vs call()
vs apply()
Method | When to Use | Arguments Format | Executes Function Immediately? |
---|---|---|---|
call() | Set this & call instantly | Comma-separated | ✅ Yes |
apply() | Set this & call instantly | Array of arguments | ✅ Yes |
bind() | Set this & call later | Comma-separated | ❌ No (returns new function) |
🧾 Summary
bind()
creates a new function withthis
permanently set.- Useful when passing methods as callbacks or in event listeners.
- Allows partial function application by pre-setting arguments.