JavaScriptMedium
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
thiscannot be changed again, not even bycall,applyor anotherbind. newoverrides it: calling a bound function withnewignores the boundthis(the pre-filled arguments still apply).- Arrow functions ignore
bind'sthisbecause they never have their own. - Each
bindcall creates a new function, soremoveEventListenermust receive the exact same bound reference you added.
Modern alternatives
- Arrow functions in class fields (
handle = () => {...}) keepthisautomatically. - 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};78const lost = user.greet;9console.log(lost()); // Hello, I'm undefined - `this` was lost1011const bound = user.greet.bind(user);12console.log(bound()); // Hello, I'm Ada13setTimeout(bound, 0); // safe as a callback1415// Partial application: pre-fill arguments16const sayHi = user.greet.bind(user, "Hi");17console.log(sayHi()); // Hi, I'm Ada1819function multiply(a, b) {20 return a * b;21}22const triple = multiply.bind(null, 3);23console.log(triple(7)); // 212425// A bound `this` cannot be changed again26const other = { name: "Grace" };27console.log(bound.call(other)); // Hello, I'm Ada2829// Each bind creates a new function30console.log(user.greet.bind(user) === user.greet.bind(user)); // false31// -> 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.