What is bind()?

fn.bind(thisArg, ...args) returns a new function with this permanently set to thisArg and, optionally, some leading arguments pre-filled; unlike call and apply, it does not run the function.

Why you need it

Methods lose their this when passed around as callbacks: setTimeout(user.greet, 100) calls greet with no object. bind fixes this once so the function works wherever it is called from.

Typical uses

  • Passing methods as callbacks or event handlers.
  • Partial application: const double = multiply.bind(null, 2).
  • Older React class components bound handlers in the constructor (this.handleClick = this.handleClick.bind(this)).

Rules

  • A bound function's this cannot be changed again, not even by call, apply or another bind.
  • new overrides it: calling a bound function with new ignores the bound this (the pre-filled arguments still apply).
  • Arrow functions ignore bind's this because they never have their own.
  • Each bind call creates a new function, so removeEventListener must receive the exact same bound reference you added.

Modern alternatives

  • Arrow functions in class fields (handle = () => {...}) keep this automatically.
  • Inline arrows: setTimeout(() => user.greet(), 100).

Code example

js
1const user = {
2 name: "Ada",
3 greet(greeting = "Hello") {
4 return `${greeting}, I'm ${this?.name}`;
5 },
6};
7
8const lost = user.greet;
9console.log(lost()); // Hello, I'm undefined - `this` was lost
10
11const bound = user.greet.bind(user);
12console.log(bound()); // Hello, I'm Ada
13setTimeout(bound, 0); // safe as a callback
14
15// Partial application: pre-fill arguments
16const sayHi = user.greet.bind(user, "Hi");
17console.log(sayHi()); // Hi, I'm Ada
18
19function multiply(a, b) {
20 return a * b;
21}
22const triple = multiply.bind(null, 3);
23console.log(triple(7)); // 21
24
25// A bound `this` cannot be changed again
26const other = { name: "Grace" };
27console.log(bound.call(other)); // Hello, I'm Ada
28
29// Each bind creates a new function
30console.log(user.greet.bind(user) === user.greet.bind(user)); // false
31// -> keep the reference you pass to addEventListener so you can remove it later

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app