iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Function bind()

fn.bind(thisArg, …args) returns a new function with this permanently fixed. Optional pre-filled arguments enable partial application.

Locking in this

JS
const user = { name: "Ada", greet() { return `Hi, ${this.name}!`; } };

const greet = user.greet;
greet();                        // "Hi, undefined!" — lost this

const boundGreet = user.greet.bind(user);
boundGreet();                   // "Hi, Ada!" — bound forever
setTimeout(boundGreet, 100);    // still works

Partial application

JS
function multiply(a, b) { return a * b; }

const double = multiply.bind(null, 2);
double(5);          // 10
double(7);          // 14

// Curry-ish event handlers
function setColor(color, e) { e.target.style.color = color; }
button.addEventListener("click", setColor.bind(null, "red"));

bind vs call vs apply

Call styleInvokes the function?Returns
fn.call(this, …args)Yes, nowResult of the call
fn.apply(this, [args])Yes, nowResult of the call
fn.bind(this, …args)No — laterA new function

Modern alternatives

JS
// Arrow wrapper — same effect, often clearer
const boundGreet = () => user.greet();

// Class field — auto-bound, can be passed around
class Toggle {
  state = false;
  flip = () => { this.state = !this.state; };
}
Tip: An arrow function and bind aren't quite identical — bind hard-binds even against future call/apply. Arrows ignore call-site this too, but you can't reuse them as constructors.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Function bind()!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Partial-apply `multiply(2, x)` into a one-arg `double`.

const double = multiply. (null, 2);

Test yourself

Q1. `fn.bind(obj)` returns…
Q2. Pre-filling args with bind enables…
Q3. A class field `flip = () => …` is…

Discussion

Loading…