bind, and Writing It Yourself
bind does not call a function. It returns a new one with this permanently fixed, and writing your own version is the clearest way to understand it.
bind returns a new function whose this can never be changed again, rather than calling immediately. It can also pre-fill leading arguments. Implementing it yourself in six lines makes both behaviours obvious.
EXERCISE
1bind Returns a Function, It Does Not Call One
This is the whole difference from call and apply, and getting it wrong produces a very recognisable bug.
call and apply run the function immediately. bind does not run anything. It hands you back a new function that remembers the this you supplied, to be called whenever you like.
The difference in two lines:
function greet() {
return `Hi, ${this.name}`;
}
const user = { name: "Ada" };
console.log(greet.call(user)); // "Hi, Ada" <- a string, called now
console.log(greet.bind(user)); // [Function: bound greet] <- a function
const bound = greet.bind(user);
console.log(bound()); // "Hi, Ada" <- called later
The recognisable bug is passing greet.bind(user) where a value was expected, or calling greet.call(user) where a callback was expected. One gives you a function where you wanted a string; the other runs immediately and hands over the result instead of the function.
Why deferring matters: callbacks:
const counter = {
count: 0,
increment() {
this.count += 1;
},
};
// Broken: setTimeout calls increment with no object before the dot.
setTimeout(counter.increment, 100); // TypeError, or a silent no-op
// Fixed: hand over a function that already knows its this.
setTimeout(counter.increment.bind(counter), 100);
You cannot use call here. setTimeout needs a function to call later, and call would have run increment immediately and passed its return value, which is undefined.
The binding is permanent, which is the part people are surprised by:
function show() {
return this.label;
}
const bound = show.bind({ label: "first" });
console.log(bound()); // first
console.log(bound.call({ label: "second" })); // first, not second
console.log(bound.bind({ label: "third" })()); // first, not third
Once bound, a function's this cannot be changed again. Not by call, not by apply, not by a second bind. This is deliberate: the guarantee is what makes a bound callback safe to pass anywhere.
The one thing that does override it is new, as rule 1 promised:
function Person(name) {
this.name = name;
}
const Bound = Person.bind({ label: "ignored" });
const p = new Bound("Ada");
console.log(p.name); // Ada, the bound this was discarded
Say it as a sentence when you are choosing: call means "run this now with that this", bind means "give me a version of this that always has that this". If the next thing you do with the result is pass it somewhere, you wanted bind. If the next thing is use its value, you wanted call.
EXERCISE
2Partial Application: Pre-filling Arguments
bind takes arguments as well as a this, and any you supply are locked in ahead of the ones passed later.
bind has a second ability that gets much less than the this part and is arguably more useful day to day.
Arguments after the first are pre-filled:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
const triple = multiply.bind(null, 3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(double(100)); // 200
null is the this, ignored here because multiply never uses it. The 2 is locked into the first parameter, so the returned function takes only what remains.
This is called partial application: fixing some arguments now and supplying the rest later. Unit 10 covers currying, which is the same idea taken further.
Pre-filled arguments always come first:
function log(level, time, message) {
return `[${level}] ${time}: ${message}`;
}
const logError = log.bind(null, "ERROR");
console.log(logError("10:30", "Disk full"));
// [ERROR] 10:30: Disk full
const logErrorNow = log.bind(null, "ERROR", "10:30");
console.log(logErrorNow("Disk full"));
// [ERROR] 10:30: Disk full
Each bind consumes parameters from the left. That ordering is fixed, which is why functions designed for partial application put their most stable arguments first and their most variable argument last.
A practical use you will actually reach for:
function handleClick(action, event) {
console.log(`${action} clicked`);
}
// Each handler is a distinct function with its action already fixed:
const onSave = handleClick.bind(null, "save");
const onDelete = handleClick.bind(null, "delete");
onSave({ type: "click" }); // save clicked
onDelete({ type: "click" }); // delete clicked
One function, several specialised versions, no duplication and no wrapper arrow needed.
Pro Tip:
bindis doing two separate jobs and you rarely want both at once. When you passnullas the first argument, you are ignoring thethisjob entirely and using it purely for partial application. That is a perfectly normal thing to do, and seeingbind(null, ...)in a codebase should read as "specialise this function", not as anything to do withthis.
EXERCISE
3Writing bind From Scratch
Six lines reproduce everything bind does, and implementing it is the point at which the whole unit becomes solid.
This is a classic interview task, and it is on the list for a good reason: you cannot write it without having understood this, closures, and rest parameters at the same time.
The implementation:
Function.prototype.myBind = function (thisArg, ...boundArgs) {
const fn = this; // the function myBind was called on
return function (...callArgs) {
return fn.apply(thisArg, [...boundArgs, ...callArgs]);
};
};
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const bound = greet.myBind({ name: "Ada" }, "Hello");
console.log(bound("!")); // Hello, Ada!
Line by line, because every line is carrying something:
// Function.prototype.myBind = function (...)
// Defined on Function.prototype, so every function inherits it.
// Exactly how the real bind is available everywhere. Unit 1's chain at work.
// const fn = this;
// Inside myBind, `this` is the function it was called on. In `greet.myBind(...)`
// the object before the dot is `greet`, so rule 3 gives us the function itself.
// return function (...callArgs) { ... }
// Returns rather than calls. This is the deferral that defines bind.
// The closure keeps `fn`, `thisArg` and `boundArgs` alive for later.
// fn.apply(thisArg, [...boundArgs, ...callArgs])
// apply, because the arguments are already an array.
// Bound arguments first, then call-time ones, which is the ordering rule.
Notice that myBind had to use a normal function for the returned value, not an arrow. An arrow would have no this of its own, so fn.apply would still work, but a bound function must also behave correctly when called with new, and an arrow cannot be constructed.
Testing it against the real thing:
function multiply(a, b) {
return a * b;
}
const doubleReal = multiply.bind(null, 2);
const doubleMine = multiply.myBind(null, 2);
console.log(doubleReal(5), doubleMine(5)); // 10 10
const obj = { name: "Ada" };
function who() {
return this.name;
}
console.log(who.bind(obj)(), who.myBind(obj)()); // Ada Ada
The real bind does a little more, including handling new correctly and setting the returned function's name and length. For every ordinary use, these six lines are the whole behaviour, which is why it is a fair thing to ask for on a whiteboard.
If you can write this from memory you have demonstrated four things at once: that this is decided at the call site, that a closure keeps its captured values alive, that rest and spread let you pass an unknown number of arguments through, and that a function is a value you can return. That is why it is asked so often, and it is worth practising until it is quick.
