Function Bind in JavaScript
? Function.prototype.bind() in JavaScript
What is bind()?
bind()creates a new function with a fixedthiscontext and optionally prepends arguments.It does not call the function immediately but returns a new function you can call later.
Useful to lock the value of
thisfor functions used as callbacks or event handlers.
Syntax
const boundFunc = func.bind(thisArg[, arg1[, arg2[, ...]]]);thisArg: The value to bind asthis.arg1, arg2, ...: Optional arguments to prepend to the new function.
Example 1: Binding this
const person = { name: "John", greet() { console.log("Hello, " + this.name); }};const greet = person.greet;greet(); // undefined or global contextconst boundGreet = person.greet.bind(person);boundGreet(); // Hello, JohnExample 2: Partial Application (Pre-filling Arguments)
function multiply(a, b) { return a * b;}const double = multiply.bind(null, 2);console.log(double(5)); // 10console.log(double(10)); // 20Key Points
bind()returns a new function.It does not invoke the original function immediately.
It fixes the
thiscontext for the new function.You can also fix some initial arguments (partial application).
Difference Between bind(), call(), and apply()
| Method | Calls Function Immediately? | Arguments Format | Returns New Function? |
|---|---|---|---|
call() | Yes | Comma-separated | No |
apply() | Yes | Array or array-like | No |
bind() | No | Comma-separated (pre-filled) | Yes |
Summary Table
| Feature | bind() |
|---|---|
| Returns new function | ? |
Fixes this context | ? |
| Partial arguments | ? |
| Calls immediately | ? |
Want to see how bind() is used in event handlers or how to create your own bind function polyfill?